我怎么知道我的所有$ http GET请求都已完成?

Sha*_*nis 0 angularjs

使用AngularJs 1.6.5我使用for循环进行多个$ http GET调用.这是代码: -

for(var i=0; i < 11; i++){  
    var url = "/api/learner_qa/" + i;   
    $http.get(url).then(successCallback, errorCallback);    
    function successCallback(response){
        console.log(response);
    };
    function errorCallback(error){
        console.log(error);
    };
};
Run Code Online (Sandbox Code Playgroud)

我想要做的是在完成所有GET请求时触发一个函数.

我在这里提到了答案,并想知道如何在我的情况下在阵列上完成这个?

Sra*_*van 6

你需要一次解决多个promises的时候可能会出现这种情况,这很容易通过$q.all()传入一个数组或一个promises对象来实现,这.then()两个promises会在解析后调用:

你可以把一个arraypushhttp通话到它

var array  = [];
for(var i=0; i < 11; i++){  
    var url = "/api/learner_qa/" + i;   
    array.push($http.get(url))
};

$q.all(array).then(function(response) {
     console.log(response)
}).catch(function(error){
    console.log(error)
});
Run Code Online (Sandbox Code Playgroud)

使用它code,response一旦你requests成功,就会有了.

这是一个示例文档