arrays - 将多个$http返回数据按调用顺序赋值给一个数组

标签 arrays json angularjs http

$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/

相关文章:

javascript - 更新 Angular 折叠面板中的数组

javascript - 改变 JSON 对象的 React 状态 将数组存储为值

javascript - 如何在 angularjs 中的简单获取请求 json 之后添加事件监听器?

javascript - AngularJS:使用 $scope.$watch 和 Controller 作为语法

C - 指向随机值的指针

C简单文件整数计数程序实现问题

递归函数上的 char * 数组操作

ruby-on-rails - 在 Ruby on Rails 中从 JSON 制作表格?

ios - 使用 Angular.js 和 iOS 客户端对 Node.js 应用程序进行身份验证

javascript - 使用 $scope.$emit() 在组件之间传递数据