Angular $ http then allow multiple calls in _.each

I am trying to extract some data from $ http inside _.each and show the merged data in $ scope.tasksData.

But the problem in _.each is executed later and returns null first. Please indicate how to resolve this.

thank

var tasksList, processingStageId;

var apiURL = "http://localhost:9080/caseDetails/" + $stateParams.caseId + "?_=1461046349867";



var stagesList = $http.get(apiURL).then(function(resdata, status, headers, config) {

return resdata;

}).then(function(stagesData) {

stageId = stagesData.data.childStages;
var allTasksData = [];
var self = this;

_.each(stageId, function(item) {
    var stagesApiURL = "http://localhost:9080/stageDetails/" + item.stage.stageId;

    $http.get(stagesApiURL).then(function(taskData, status, headers, config) {
        //_.extend(allTasksData, taskData.data);            
        allTasksData.push(taskData.data);

    });
});

return allTasksData;

}).then(function(allTasksData) {
console.log("Hello");

_.each(allTasksData, function(data) {
    $scope.tasksData.concat(data);
});
});
+4
source share
3 answers

To get data after resolving the entire request, use $ q.all ([prom, prom, prom])

.then(function(stagesData){
    var stageId = stagesData.data.childStages;
    var tasks = [];

    _.each(stageId, function(item){
        var stagesApiURL = "http://localhost:9080/stageDetails/" + item.stage.stageId;
        var req = $http.get(stagesApiURL).then(function(taskData, status, headers, config){            
            return taskData.data;
        });
        tasks.push(req);
    });

    //Merge all promise request. Resolve when all request resolved
    return $q.all(tasks);

})
/**
 * allTasksData - [taskData.data, taskData.data , ...]
 */
.then(function(allTasksData){
  ...
});
+2
source

You need to enter the service $qand use the function$q.all

var stagesList = $http.get(apiURL).then(function(resdata, status, headers, config) {
  return resdata;
})
.then(function(stagesData) {
  stageId = stagesData.data.childStages;

  var self = this;

  return $q.all(
    _.map(stageId, function(item) {
      var stagesApiURL = "http://localhost:9080/stageDetails/" + item.stage.stageId;

      return $http.get(stagesApiURL).then(function(taskData, status, headers, config) {
          return taskData.data;
      });
    })
  );
})
.then(function(allTasksData) {
  console.log("Hello");

  _.each(allTasksData, function(data) {
      $scope.tasksData.concat(data);
  });
});

: map each promises. promises $q.all, taskData.data .

0

$q.all() .

According to the documentation, this is:

Combines several promises into one promise, which is resolved by resolving all input promises.

You record all your calls, and then, when all of them are allowed, you do what you need with your data.

Here is an example (not mine) example of how it works.

0
source

All Articles