gpt4 book ai didi

angularjs - 在AngularJs中链接Ajax调用

转载 作者:行者123 更新时间:2023-12-03 07:56:56 24 4
gpt4 key购买 nike

我想在一个链中进行多个Ajax调用。但我也想在每次通话后对数据进行按摩,然后再进行下一次通话。最后,当所有调用都成功时,我想运行其他代码。

我正在为我的Ajax调用使用Angular $ http服务,并坚持这一点。

可能吗?

最佳答案

是的,由于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
});

关于angularjs - 在AngularJs中链接Ajax调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16284403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com