AngularJS: forEach http get data -等待其他方法,直到所有来自循环的数据被加载

AngularJS: forEach http get data - wait for other method untill all data from loop is loaded

本文关键字:循环 加载 数据 get http forEach data 方法 其他 等待 AngularJS      更新时间:2023-09-26

我的代码是:

      var commentAuthorIds = [];
      $scope.commentAuthors = [];
      angular.forEach($scope.news.Comments, function(el) {
        if (angular.isDefined(el.AuthorId)){
          commentAuthorIds.push(el.AuthorId);
        }
      });
      commentAuthorIds = $filter('unique')(commentAuthorIds);
      var promises = [];
      angular.forEach(commentAuthorIds, function(el) {
        promises.push($scope.getCommentsAuthorData(el));
      });
      $q.all(promises).then(function(){
        console.log('all data loaded!');
        angular.forEach($scope.news.Comments, function(el) {
          angular.forEach($scope.commentAuthors, function(subEl) {
            if (el.AuthorId === subEl.Id){
              el.Author = response.FirstName + ' ' + response.LastName;
              el.Thumbnail = response.Thumbnail;
            }
          });
        });
      });
      $scope.getCommentsAuthorData = function(userId){
        $http.get('/app/' + $scope.company.Id + '/users/' + userId, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        .success(function(response) {
          $scope.commentAuthors.push(response);
        });
      };

和i需要在$q.all(promises).then(function(){...加载后才调用angular.forEach($scope.news.Comments, function(el) {...

我做错了什么?我的代码不工作(

)

getCommentsAuthorData不返回承诺…在$http

前添加返回
$scope.getCommentsAuthorData = function(userId){
    return $http.get('/app/' + $scope.company.Id + '/users/' + userId, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
  };

基于此:

all函数返回一个值数组的promise。当这个类的实现值原来的承诺,按原来的顺序排列。如果其中一个如果承诺被拒绝,则立即返回承诺已拒绝,未等待批处理的剩余部分。

在您的情况下这可能是一个问题....所以使用$q扩展名可以解决这个问题,将它添加到您的应用程序中然后你可以这样做:

$q.allSettled(promises).then(function(responses){
      angular.forEach(responses,function(response){
            if(response.status!="rejected"){
                 $scope.commentAuthors.push(reponse.value);
            }else{
                 console.log(response.reason);
            }
      });
});