在我的 AngularJS 应用程序中,我通过 Controller 上的 $http.post(我使用的是 json rpc API)获取数据,然后我使用
呈现该数据(项目数组)<div ng-repeat="item in arrayItems">
{{ makeANewHttpRequest(item.relatedItemId).propertyName }}
</div>
我需要的是实现 $scope.makeANewHttpRequest(itemId) 函数,它的调用次数与 arrayItems.length 一样多,并从新的 $http.post 请求中返回 relatedItem 对象。
我该怎么做? 这是一个好的做法吗?
最佳答案
首先你需要创建一个工厂来负责调用已经暴露给其他人的$http.post
,它会返回promise对象。您可以通过添加 dataService
工厂作为对 Controller 依赖项的引用来调用该服务方法。 Controller 将调用服务函数,如 dataService.getData(url, data)
& 在每个 promise 解决时,它将增加计数器,更新数据,然后调用下一个 post 如果 arrayItems
计数不超过计数器。
工厂
var myModule = angular.module('myModule', []);
myModule.factory('dataService', function($http) {
var getData = function(url, data) {
return $http.post(url, {
data
}).then(function(res) {
return res.data;
});
};
return {
getData: getData
}
});
Controller
myModule.controller('mainCtrl', function($scope, dataService) {
//other code
$scope.counter = 0;
$scope.makeANewHttpRequest = function(id) {
dataService.getData(url+id, data).then(function(data) {
$scope.data = data; //updated the data each time when response received
++$scope.counter; //increment counter
if ($scope.counter >= $scope.arrayItems.length) //check counter should not exceed limit
$scope.makeANewHttpRequest(id);
});
}
});
HTML
ng-click="counter=0;$scope.makeANewHttpRequest(id)" //clear count and call method
希望对您有所帮助,谢谢。
关于javascript - 来自模板 ng-repeat 的 AngularJS 子 $http.post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28887104/