代码之家  ›  专栏  ›  技术社区  ›  Mahesh Sanjeewa

AngularJS如何检查多个http请求是否完成,以及在所有响应完成后执行一些操作

  •  1
  • Mahesh Sanjeewa  · 技术社区  · 7 年前

    嗨,我正在通过for循环发送HTTP请求,我想知道在所有响应都出现之后我该怎么做。

    这是我的密码。

    $scope.totalIdSet = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23...ect] total id count will be  more than 200
    
    for (var k = 0; k < $scope.totalIdSet.length; k++) {
    
    MydocumentsServices.downloadDoc($scope.totalIdSet[k], $scope.loggedUserInfo.access_token).then(function (res) {
    
                    }, function () {
    
                    });
                }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Pankaj Parkar    7 年前

    确保您确实创建了 httpRequests . 同样的,你也要回报你的承诺 downloadDoc $q.all 直到所有的承诺都实现。

    function downloadDoc (totalIdSet, access_token) {
       return $http.post('someurl', totalIdSet, {headers: {Authorization: access_token}})
    } 
    

    控制器

    $scope.totalIdSet = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
    var promises = []
    for (var k = 0; k < $scope.totalIdSet.length; k++) {
        var promise = MydocumentsServices.downloadDoc($scope.totalIdSet[k], $scope.loggedUserInfo.access_token)
        promises.push(promise)
    }
    $q.all(promises).then(function(responses) {
      console.log(responses)
    
    }, function() {
    
    });
    
        2
  •  0
  •   holydragon    7 年前

    你可以用 $q

    例如,

    $q.all(arrayOfHttpFunctions).then(responses => {
        // Do your thing here
    })
    

    哪里 arrayOfHttpFunctions