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

查看:116
本文介绍了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' })
});

而我的应用程序/ JS /服务/ 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' })

和我的控制器应用程序/ JS /控制器/ transactionController.js 看起来

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 

什么是我做错了?

What is that I am doing wrong here?

推荐答案

Category.query()是异步的。它会立即返回一个空数组,并从请求增加的结果后,当响应到达 - 从<一个href=\"http://docs.angularjs.org/api/ngResource.%24resource\">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:

要实现这一点很重要调用$资源对象的方法
  立即返回取决于一个空引用(对象或数组
  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天全站免登陆