The right way to communicate with Aach Ajax calls in Angular

I need to update the data for each object in the array using a for loop, and as soon as all the data is captured, run the function. I don't want to mix jQuery in this and do the right Angular way to do

That's what I'm 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 }; 

Service is defined as.

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

How to get a callback when all pulling has been done in a for loop?

+6
source share
1 answer

The result of your call to $http(...) is a promise. This means that you can use $q.all to wait for the array 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 }); }; 
+19
source

Source: https://habr.com/ru/post/956448/


All Articles