我有一个REST API,我想从AngularJS服务中调用,如下所示:
angular.module('myModule').service('MyApi', ['$http', function($http) {
return ({
resources: resources,
details: details
});
function resources() {
return $http.jsonp('/api/resources');
}
function details(key) {
return $http.jsonp('/api/details/' + id);
}
}]);
那里删除了其他重要的实现细节,例如身份验证。该API由第三方提供,因此无法更改。
GET /api/resources
返回类似:
[{ "key": "one" }, { "key": "two" }]
GET /api/details/one
返回类似:
{ "count": 5 }
然后,我有一个要在其中调用的控制器MyApi.resources()
,等待结果,然后对每个结果调用MyApi.details(resource)
。当最后一次调用MyApi.details(resource)
完成时,我想运行一个函数来汇总一组详细信息中的某些结果,但最终我无法弄清楚如何触发此结果。
我的控制器当前如下所示:
angular.module('myModule').controller('MyCtrl', ['$scope', 'MyApi', function($scope, MyApi) {
$scope.results = new Array();
MyApi.resources().then(function(response) {
var resources = response.data;
var length = resources.length;
for (var i = 0; i < length; i++) {
MyApi.details(resources[i].key).then(function(response) {
$scope.results.push(response.data.count);
});
}
});
// how do I get this line to run only after all the results are returned?
$scope.total = $scope.results.reduce(function(a, b) { return a + b; }, 0);
}]);
最后实现聚合的最佳方法是什么?
您可以使用deferred的函数$ q.all。
angular.module('myModule').controller('MyCtrl', ['$scope', 'MyApi', '$q', function($scope, MyApi, $q) {
$scope.results = new Array();
MyApi.resources().then(function(response) {
var resources = response.data;
var length = resources.length;
var defer = $q.defer();
var promises = [];
angular.forEach(resources, function(value) {
promises.push(MyApi.details(resources[i].key));
});
$q.all(promises).then(function() {
$scope.total = $scope.results.reduce(function(a, b) { return a + b; }, 0);
});
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句