gpt4 book ai didi

javascript - AngularJS:服务查询返回零结果

转载 作者:数据小太阳 更新时间:2023-10-29 05:00:19 26 4
gpt4 key购买 nike

我的 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' })

我的 Controller 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 :

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.

如果您需要在 Controller 中访问结果,您应该在回调函数中这样做:

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

关于javascript - AngularJS:服务查询返回零结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16389362/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com