$scope.iter = 0;
$scope.myArray.forEach(function () {
$http.get($scope.myArray[$scope.iter].URL)
.success(function (data) {
$scope.myArray2.push(data);
//$scope.myArray2[$scope.iter]=data
});
$scope.iter++;
})
上面的代码有效,但我希望 myArray2 中的结果与调用时的顺序相同。我知道我不能期望 $scope.myArray2[$scope.iter]=data 工作,但这就是我需要的。
我查看了有关 promises 的 Angular 文档,但无法弄清楚如何将其用于上述目的。
最佳答案
您可以将 get 请求中的所有 promise 放在一个数组中并使用 $q.all()
创建一个 promise ,当所有潜在的 promise 都解决时解决。然后,您可以按照将响应添加到请求数组的顺序迭代响应,并将每个响应的数据按顺序推送到数组中...
function controller ($scope, $q) {
// ...
var requests = [];
var $scope.myArray2 = [];
angular.forEach($scope.myArray, function (value) {
requests.push($http.get(value.URL));
});
$q.all(requests).then(function(results) {
angular.forEach(results, function(result) {
$scope.myArray2.push(result.data);
});
});
}
关于arrays - 将多个$http返回数据按调用顺序赋值给一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24113633/