AngularJS:服务查询返回零结果 [英] AngularJS: service query returning zero result

查看:21
本文介绍了AngularJS:服务查询返回零结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 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 看起来像

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

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 看起来像

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

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

When I run my app, i see console.log as

all categories -  0 

我在这里做错了什么?

推荐答案

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

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:

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

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

这篇关于AngularJS:服务查询返回零结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆