javascript Angular.js - 需要使用服务的回调
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17659003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular.js - callback needed using service
提问by joakimnorberg
I have a setup with a service to fetch a list of items, a controller to do something to that list, and a view to iterate through and display each item.
我有一个服务来获取项目列表,一个控制器对该列表执行某些操作,以及一个视图来迭代和显示每个项目。
Thing is, my items are links to RSS feeds and in the controller I want to parse through these RSS feeds and set up the model data for the view to handle.
事实是,我的项目是 RSS 提要的链接,在控制器中我想通过这些 RSS 提要解析并设置模型数据以供视图处理。
Now, there are some more modifications to the modelling to be done (I need to model the actual RSS feed content), but my first problem is that the data fetched by the service is not modifiable in my controller (since the call hasn't finished, at the time I try to access it, I guess). Basically it's just an empty array if i write it to the console.
现在,需要对建模进行更多修改(我需要对实际的 RSS 提要内容进行建模),但我的第一个问题是服务获取的数据在我的控制器中不可修改(因为调用没有完成,当时我尝试访问它,我猜)。如果我将它写入控制台,基本上它只是一个空数组。
So I'd need to know how to trigger the data operations in the controller once the service call has finished.
所以我需要知道如何在服务调用完成后触发控制器中的数据操作。
Thanks!! // Joakim
谢谢!!// 乔金
Service code:
服务代码:
angular.module('itemfeedServices', ['ngResource']).
factory('Item', function($resource){
return $resource('items/:itemId.json', {}, {
query: {method:'GET', params:{itemId:'items'}, isArray:true}
});
});
Controller code:
控制器代码:
function ItemListCtrl($scope, Item) {
$scope.items = Item.query();
console.log($scope.items); // gives []
}
采纳答案by mael
Basically, I think you want a callback? The documentation says:
基本上,我认为您想要回调?文档说:
The action methods on the class object or instance object can be invoked with the following parameters:
HTTP GET "class" actions: Resource.action([parameters], [success], [error])
non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
non-GET instance actions: instance.$action([parameters], [success], [error])
So, using:
所以,使用:
Item.query({}, function() {
//you callback
});
should work.
应该管用。
回答by bluehallu
While callbacks will work, it's not the Angular way to do it. Check out the promises patternand Angular own implementation of it, $q
虽然回调会起作用,但这不是 Angular 的做法。查看promises 模式和 Angular 自己的实现,$q