AngularJS: service request returning null result

my app.js looks like

 var app = angular.module('pennytracker', [ '$strap.directives', 'ngCookies', 'categoryServices' ]); app.config(function($routeProvider) { console.log('configuring routes'); $routeProvider .when('/summary', { templateUrl: '../static/partials/summary.html'}) .when('/transactions', { templateUrl: '../static/partials/transaction.html', controller: 'AddTransactionController' }) }); 

while my app/js/services/categories.js looks like

 angular.module('categoryServices', ['ngResource']). factory('Category', function($resource){ return $resource( '/categories/:categoryId', {categoryId: '@uuid'} ); }); 

and I have a route like

  .when('/transactions', { templateUrl: '../static/partials/transaction.html', controller: 'AddTransactionController' }) 

and my controller app/js/controllers/transactionController.js looks like

 function AddTransactionController($scope, $http, $cookieStore, Category) { // some work here $scope.category = Category.query(); console.log('all categories - ', $scope.category.length); } 

When I launch my application, I see console.log as

 all categories - 0 

What am I doing wrong here?

+6
source share
1 answer

Category.query() is asynchronous. It immediately returns an empty array and adds the result from the request later when the answer arrives - from http://docs.angularjs.org/api/ngResource.$resource

It is important to understand that calling the resource object's method $ resource immediately returns an empty reference (object or array depending on IsArray). As soon as the data is returned from the server, the existing link is filled with actual data. This is a useful trick since the resource is usually assigned to a model, which is then visualized by presentation. The presence of an empty object does not lead to rendering, as soon as the data comes from the server, then the object is populated with data, and the view automatically re-displays the new data.

If you need access to the result in your controller, you must do this in a callback function, for example:

 $scope.category = Category.query(function(){ console.log('all categories - ', $scope.category.length); }); 
+15
source

Source: https://habr.com/ru/post/944328/


All Articles