我想在链中进行多个Ajax调用.但我也希望在每次通话之后按下数据,然后再拨打下一个电话.最后,当所有调用成功时,我想运行一些其他代码.
我正在为我的Ajax调用使用Angular $ http服务,并希望坚持这一点.
可能吗?
pko*_*rce 53
是的,这是由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
});
Run Code Online (Sandbox Code Playgroud)
您也可以将后处理和下一个$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
});
Run Code Online (Sandbox Code Playgroud)
接受的答案是好的,但它没有解释捕获和最终真正把锦上添花的方法.这个诺言很大的文章让我直.以下是基于该文章的一些示例代码:
$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();
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
18434 次 |
最近记录: |