在Angular中处理forEach Ajax调用的正确方法

时间:2021-10-22 11:48:20

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

我需要使用for循环更新数组中每个对象的数据,并且一旦捕获了所有数据,就运行一个函数。我不想在这里混合使用jQuery,并采用适当的Angular方式

Here is what I am 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 ?

当在for循环中完成所有拉动时,如何收到回调?

1 个解决方案

#1


19  

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.

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

$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
    });
};

#1


19  

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.

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

$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
    });
};