处理用foreach阿贾克斯适当的方式调用角 [英] Proper way of dealing with forEach Ajax calls in Angular

查看:139
本文介绍了处理用foreach阿贾克斯适当的方式调用角的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用for循环更新在阵列的每个对象中的数据,一旦所有的数据被捕获,运行一个函数。我不想在这个混合jQuery和做到这一点做的正确的方式角

I need to update the data for each object in an array using a for loop and once all the data is captured, run a function. I don't want to mix jQuery in this and do it the proper Angular way of doing

下面是我在做什么,

    $scope.units = ['u1', 'u2', 'u3'];
    $scope.data = null;
    //get individual unit data
    $scope.getUnitData = function(unit){
        service.getUnitData(unit).success(function(response){
             $scope.data.push({'id' : response.id , 'value' : response.value});
        });
    };

    $scope.updateAllUnits = function(){
    $scope.data = null ; //remove existing data
    angular.forEach($scope.units,function(val,key){
      $scope.getUnitData(val);
    };
    console.log($scope.data); // Need to show all the data but currently it does not as the for    each loop didn't complete
    };

该服务被定义为。

The service is defined as.

app.factory('service',function($http){
     return {
        getUnitData : function(unit){
        return $http({
            url : myURL,
            method : 'GET',
            params : {'unit' : unit}
            });
        }

     }

});

我如何收到一个回调时,所有的拉动已经在做了循环?

How do I receive a callback when all the pulling has been done in the for loop ?

推荐答案

$ HTTP(...)调用的结果是一个承诺。这意味着您可以使用 $ q.all 来等待他们的数组来完成的。

The result of your $http(...) call is a promise. This means you can use $q.all to wait for an array of them to complete.

$scope.updateAllUnits = function(){
    $scope.data = null ; //remove existing data
    var promises = [];
    angular.forEach($scope.units,function(val,key){
      promises.push($scope.getUnitData(val));
    });
    $q.all(promises).then(function success(data){
      console.log($scope.data); // Should all be here
    }, function failure(err){
      // Can handle this is we want
    });
};

这篇关于处理用foreach阿贾克斯适当的方式调用角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆