在AngularJs中调用Ajax调用

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

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

可能吗?

是的,这是由AngularJS处理非常优雅,因为它的$http服务围绕PromiseAPI构build。 基本上, $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 }); 

被接受的答案是好的,但它并没有解释真正把锦上添花的结果和方法。 这篇关于承诺的伟大文章让我很直白。 以下是一些基于该文章的示例代码:

 $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(); });