byCoder
byCoder

Reputation: 9184

AngularJS: forEach and http get data - wait until all was loaded

Lets say i have article with comments.

And my data is similar:

  {ArticleId...., someFields...., Comments: [{AuthorId:1, Text:''}, {AuthorId:2, Text:''}, {AuthorId:3, Text:''}]}

and i'm getting user data (like avatar, name etc...) via getting it: /user/{id}

(but i load this only after user click's on comments...)

$scope.getUserData = function(el) {
  $http.get(settings.apiBaseUri + '/app/users/' + el.AuthorId, {
    headers: {
      'Content-Type': 'application/json',
      'Pragma': 'no-cache',
      'Cache-Control': 'no-cache',
      'If-Modified-Since': ''
    }
  })
  .success(function(response) {
    /*store some data*/
  });
});

$scope.getArticleData = function(){
    angular.forEach($scope.article.Comments, function(el) {
        $scope.getUserData(el.AuthorId);
    });
    /*How here i could wait untill my forEach done all work (also all http data was loaded) and only then run my new method?*/
};

How i could wait untill my forEach done all work (also all http data was loaded) and only then run my new method?

Upvotes: 1

Views: 1327

Answers (1)

matiou
matiou

Reputation: 156

I think you could use a promise array for that, containing the promises created by $http. Something like :

$scope.getUserData = function(el) {
  var promise = $http.get(settings.apiBaseUri + '/app/users/' + el.AuthorId, {
    headers: {
      'Content-Type': 'application/json',
      'Pragma': 'no-cache',
      'Cache-Control': 'no-cache',
      'If-Modified-Since': ''
    }
  })
  .success(function(response) {
    /*store some data*/
  });
  return promise;
});

$scope.getArticleData = function(){
    var promises = [];
    angular.forEach($scope.article.Comments, function(el, promises) {
        promises.push($scope.getUserData(el.AuthorId));
    });
    $q.all(promises).then(/*Whatever you want to do*/);
};

Or prettier, like suggested by @sdgluck :

$scope.getArticleData = function(){
        var promises = $scope.article.Comments.map(function() {
          return $scope.getUserData(el.AuthorId);
        });
        $q.all(promises).then(/*Whatever you want to do*/);
    };

Upvotes: 4

Related Questions