如何在服务和控制器中使用angularjs promise链?

时间:2016-06-06 07:45:03

标签: angularjs angular-promise

我在网上找到了这个plnkr链接,但我需要使用2或3个以上的ajax调用,这不需要第一个ajax调用的参数。如何处理错误?

var app = angular.module("app", []);

app.service("githubService", function($http, $q) {

  var deferred = $q.defer();

  this.getAccount = function() {
    return $http.get('https://api.github.com/users/haroldrv')
      .then(function(response) {
        // promise is fulfilled
        deferred.resolve(response.data);
        return deferred.promise;
      }, function(response) {
        // the following line rejects the promise 
        deferred.reject(response);
        return deferred.promise;
      });
  };
});

app.controller("promiseController", function($scope, $q, githubService) {

  githubService.getAccount()
    .then(
      function(result) {
        // promise was fullfilled (regardless of outcome)
        // checks for information will be peformed here
        $scope.account = result;
      },
      function(error) {
        // handle errors here
        console.log(error.statusText);
      }
    );
});

http://plnkr.co/edit/kACAcbCUIGSLRHV0qojK?p=preview

3 个答案:

答案 0 :(得分:1)

您可以使用$q.all

var promises=[
$http.get(URL1),
$http.get(URL2),
$http.get(URL3),
$http.get(URL4)
];

$q.all(promises).then(function(response){
console.log('Response of Url1', response[0]);
console.log('Response of Url2', response[1]);
console.log('Response of Url3', response[2]);
console.log('Response of Url4', response[3]);
}, function(error){

});

我已将plunkr$q

分开

答案 1 :(得分:1)

首先,您应该为要返回承诺的每个ajax调用设置deferred变量。因此,您必须创建2-3个函数(与ajax调用一样多)并将它们保存在数组中。然后你应该使用:

$q.all([ajax1,ajax2,ajax3]).then(function(values){
    console.log(values[0]); // value ajax1
    console.log(values[1]); // value ajax2
    console.log(values[2]);}); //value ajax3

示例:

function ajax_N() {
   var deferred = $q.defer();

    http(...).then((response) => {
      deferred.resolve(response);
   }, (error) => {
      deferred.reject(error);
   });

   return deferred.promise;
}

$q.all([
        ajax_1,ajax_2,ajax_3
     ]).then(function(values) {        
          console.log(values); 
          return values;
        });

答案 2 :(得分:0)

在这种情况下使用$q.all。它会同时拨打getAccountgetSomeThing api。

var app = angular.module("app", []);

app.service("githubService", function($http, $q) {

  return {

    getAccount: function () {
      return $http.get('https://api.github.com/users/haroldrv');
    },

    getSomeThing: function () {
      return $http.get('some thing url');
    }
  };

});

app.controller("promiseController", function($scope, $q, githubService) {

  function initData () {
    $q.all([githubService.getAccount(), githubService.getSomeThing()])
      .then(
        function (data) {
          $scope.account = data[0];
          $scope.someThing = data[1];
        },
        function (error) {

        }
      );
  }
});
相关问题