AngularJS:forEach和http获取数据 - 等到所有加载完毕

时间:2015-09-18 12:48:56

标签: javascript angularjs promise

让我说我的文章有评论。

我的数据很相似:

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

我通过获取用户数据(如头像,名称等等)获取:/ user / {id}

(但我只在用户点击评论后才加载此内容...)

$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?*/
};

我如何等待,直到我的forEach完成所有工作(也加载了所有http数据),然后才运行我的新方法?

1 个答案:

答案 0 :(得分:4)

我认为您可以使用promise数组,其中包含$ http创建的promise。类似的东西:

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

或更漂亮,就像@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*/);
    };