AngularJS:服务查询返回零结果

AngularJS: service query returning zero result

本文关键字:结果 返回 查询 服务 AngularJS      更新时间:2023-09-26

我的app.js看起来像

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' })
});

而我的app/js/services/categories.js看起来像

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

,我有一个路由作为

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

我的控制器app/js/controllers/transactionController.js看起来像

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

当我运行应用程序时,我看到console.log为

all categories -  0 

我在这里做错了什么?

Category.query()是异步的。它立即返回一个空数组,并在响应到达后添加来自请求的结果—来自http://docs.angularjs.org/api/ngResource.$resource:

重要的是要意识到调用$resource对象方法立即返回一个空引用(对象或数组)isArray)。一旦数据从服务器返回,现有的引用用实际数据填充。这是一个有用的技巧因为通常资源被分配给一个模型,然后由视图渲染。拥有一个空对象将导致不渲染,一旦数据从服务器到达,对象就会被填充与数据和视图自动重新呈现本身显示新数据。

如果你需要在控制器中访问结果,你应该在回调函数中这样做:

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