Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way of dealing with forEach Ajax calls in Angular

Tags:

angularjs

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

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 ?

like image 664
lostpacket Avatar asked Oct 21 '13 20:10

lostpacket


1 Answers

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
    });
};
like image 87
Andyrooger Avatar answered Oct 19 '22 23:10

Andyrooger