【发布时间】:2016-05-12 09:30:54
【问题描述】:
我想在一个链中进行多个 Ajax 调用。但我也想在每次通话后按摩数据,然后再拨打下一个电话。最后,当 All 调用成功时,我想运行一些其他代码。
我正在为我的 Ajax 调用使用 Angular $http 服务,并希望坚持下去。
有可能吗?
【问题讨论】:
标签: angularjs
我想在一个链中进行多个 Ajax 调用。但我也想在每次通话后按摩数据,然后再拨打下一个电话。最后,当 All 调用成功时,我想运行一些其他代码。
我正在为我的 Ajax 调用使用 Angular $http 服务,并希望坚持下去。
有可能吗?
【问题讨论】:
标签: angularjs
是的,AngularJS 处理得非常优雅,因为它的$http 服务是围绕 PromiseAPI 构建的。基本上,对$http 方法的调用会返回一个promise,您可以使用then 方法很容易地链接promise。这是一个例子:
$http.get('http://host.com/first')
.then(function(result){
//post-process results and return
return myPostProcess1(result.data);
})
.then(function(resultOfPostProcessing){
return $http.get('http://host.com/second');
})
.then(function(result){
//post-process results of the second call and return
return myPostProcess2(result.data);
})
.then(function(result){
//do something where the last call finished
});
你也可以将后处理和下一个$http函数结合起来,这完全取决于谁对结果感兴趣。
$http.get('http://host.com/first')
.then(function(result){
//post-process results and return promise from the next call
myPostProcess1(result.data);
return $http.get('http://host.com/second');
})
.then(function(secondCallResult){
//do something where the second (and the last) call finished
});
【讨论】:
$q.all,似乎正在做我想做的事。但我也会试试这个。
q.all 和这里描述的解决方案是两个不同的东西。 q.all 很棒,但仅适用于并行请求,也就是说,如果您不关心它们的顺序并且一个请求不依赖于另一个请求的结果。从您的问题中,我了解到您在链接请求之后,其中一个请求需要完成,您想要检查/处理结果,然后才发出另一个请求。
公认的答案很好,但它没有解释真正锦上添花的捕获和最终方法。这个great article on promises 让我直截了当。以下是基于该文章的一些示例代码:
$scope.spinner.start();
$http.get('/whatever/123456')
.then(function(response) {
$scope.object1 = response.data;
return $http.get('/something_else/?' + $scope.object1.property1);
})
.then(function(response) {
$scope.object2 = response.data;
if ($scope.object2.property88 == "a bad value")
throw "Oh no! Something failed!";
return $http.get('/a_third_thing/654321');
})
.then(function(response) {
$scope.object3 = response.data;
})
.catch(function(error) {
// this catches errors from the $http calls as well as from the explicit throw
console.log("An error occured: " + error);
})
.finally(function() {
$scope.spinner.stop();
});
【讨论】: