链接阿贾克斯AngularJs调用 [英] Chaining Ajax calls in AngularJs
问题描述
我想提出多个阿贾克斯在调用链。但我也想使下一次调用之前每次通话后按摩的数据。最后,当所有通话是成功的,我想运行其他一些code。
我采用了棱角分明的$ HTTP服务,为我的Ajax调用,并希望坚持到底。 P>
这可能吗?
是的,这是由AngularJS处理得非常优雅,因为它的 $ HTTP
服务是围绕PromiseAPI建成。基本上,调用 $ HTTP
方法,通过使用然后
方法返回一个承诺,你能承诺链条很容易。下面是一个例子:
$ http.get('http://host.com/first')
。然后(功能(结果){
//后处理结果,并返回
返回myPostProcess1(result.data);
})
。然后(功能(resultOfPostProcessing){
返回$ http.get('http://host.com/second');
})
。然后(功能(结果){
//第二调用和返回的过程后的结果
返回myPostProcess2(result.data);
})
。然后(功能(结果){
//做一些事情,其中最后通话结束后
});
您还可以结合后期处理和明年 $ HTTP
功能以及,这一切都取决于谁是有兴趣在结果中。
$ http.get('http://host.com/first')
。然后(功能(结果){
从下一次调用//后期处理的结果和回报的承诺
myPostProcess1(result.data);
返回$ http.get('http://host.com/second');
})
。然后(功能(secondCallResult){
//做一些事情,其中第二(最后)调用完成
});
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.
I am using Angular $http service for my Ajax calls and would like to stick to that.
Is it possible?
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
});
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调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!