我有一系列带有名字和网址的城市。
$scope.cities = [{'name':'LKO','url': 'http://sm.com'},{'name':'LK1O','url': 'http://sm1.com'}]
现在我需要向城市中的网址发出请求。一个请求的响应一个接一个地到来。
我知道这可以使用promises。 但是,我无法得到确切的解决方案。
答案 0 :(得分:2)
在一系列承诺全部解决后,您可以使用$q.all()
来运行代码
var promises = $scope.cites.map(function(city) {
return $http.get(city.url).then(function(resp) {
var cityData = resp.data;
// do something with cityData here
// then return it
return cityData;
});
});
$q.all(promises, function(cityDataArray) {
// do something with array
});
这种方法假定请求不依赖于彼此,并且比递归递送要快得多
确保将$q
注入您提出这些请求的服务或控制器
答案 1 :(得分:1)
您可以使用递归循环,如下例所示:
var app=angular.module("app",[]);
app.controller("main",function($scope,$q,$http){
$scope.cities = [{'name':'LKO','url': 'http://stackoverflow.com/posts/39497624'},{'name':'LK1O','url': 'http://stackoverflow.com/posts/39497624'},
{'name':'LK21','url': 'http://stackoverflow.com/posts/39497624'}]
//recursive function
function getUrl(i){
if (typeof $scope.cities[i]=='undefined')
return; //last one
console.log("ajax to "+ $scope.cities[i].url);
$http.get($scope.cities[i].url).then( getUrl(i+1) );
};
getUrl(0);//start
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="main">
</div>
PS。我改变了这个github问题的网址。
答案 2 :(得分:1)
其他答案很复杂。这是一个更简单的一个:
const cities = [{'name':'LKO','url': 'http://sm.com'}, ...]
const queue = $q.resolve(); // get an empty promise
for(const city of cities) { // angular.forEach if you want to avoid for...of
queue = queue.then(() => $http.get(city.url).then(/* write result to scope*/))
}
你只需在循环中链接承诺。