在 AngularJs 中链接 Ajax 调用 [英] Chaining Ajax calls in AngularJs
问题描述
我想在一个链中进行多个 Ajax 调用.但我也想在每次通话后按摩数据,然后再进行下一次通话.最后,当 All 调用成功时,我想运行一些其他代码.
I would like to make multiple Ajax calls in a chain. But I also would like to massage the data after each call before making the next call. In the end, when All calls are successful, I would like to run some other code.
我正在为我的 Ajax 调用使用 Angular $http 服务,并希望坚持下去.
I am using Angular $http service for my Ajax calls and would like to stick to that.
有可能吗?
推荐答案
是的,AngularJS 非常优雅地处理了这个问题,因为它的 $http
服务是围绕 PromiseAPI 构建的.基本上,对$http
方法的调用返回一个promise,您可以使用then
方法非常轻松地链接promise.下面是一个例子:
Yes, this is handled very elegantly by AngularJS since its $http
service is built around the PromiseAPI. Basically, calls to $http
methods return a promise and you can chain promises very easily by using the then
method. Here is an example:
$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
函数,这完全取决于谁对结果感兴趣.
You could also combine post-processing and next $http
function as well, it all depends on who is interested in the results.
$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
});
这篇关于在 AngularJs 中链接 Ajax 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!