AngularJS: service query returning zero result

∥☆過路亽.° 提交于 2019-12-18 16:57:30

问题


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 as

  .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 run my app, i see console.log as

all categories -  0 

What is that I am doing wrong here?


回答1:


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

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data.

If you need to access the result in your controller you should do it in the callback function like this:

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


来源:https://stackoverflow.com/questions/16389362/angularjs-service-query-returning-zero-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!