如何在AngularJS中使用重试逻辑重用HTTP请求

时间:2014-08-22 01:36:28

标签: ajax angularjs angular-promise

是否可以在AngularJS中多次执行相同的HTTP请求?即两次没有重新定义相同的请求?

var retry = false;
var req = $http.get( 'ajax.php?a=StartSession&ref=' + code );
req.success(function(res) {
    alert(res);
});
req.error( function(res) {
    if(retry == false)
       //run request again req.get(); ?
    retry = true;
});

2 个答案:

答案 0 :(得分:4)

以前的答案在重用服务方面很好。但看起来你真的想要抽象出重试逻辑。我就是这样做的。

app.service('SessionService', ['$http', '$q', function($http, $q){

  var _this = this;
  var _maxRetryCount = 5; //Just have a maxRetryCount

  this.StartSession = function (code, retries){
      //if you dont pass retry take the maxretryCount 
      retries = angular.isUndefined(retries) ? _maxRetryCount : retries;

      return $http.get('ajax.php?a=StartSession&ref=' + code)
        .then(function(result) {
         //process and return the result
            return result.data;
        }, function (errorResponse) {
         //If retries left decrement count and make the call again.
         if(retries) {
            return _this.StartSession(code, --retries); //here we are returning the promise
         }
         //All tried done Now Fail or return some data
         return $q.reject('oops failed after retries');
    });
  }
}]);

只需在你的控制器中的任何地方注入SessionService: -

 SessionService.StartSession(code).then(function(result){
     //handle Result
  }).catch(function(){
      //handle fail condition
  });

<强> Plnkr

答案 1 :(得分:2)

这是服务和工厂的目的:

app.factory("dataFactory", ["$http", function($http) {
    return {
        call: function(code) {
            return $http.get( 'ajax.php?a=StartSession&ref=' + code )
        }
    }
}]);

注入并使用

app.controller("myCtrl", ["dataFactory", function(dataFactory) {
    var code = "myCode";
    dataFactory.call(code).success(function(res) {
        //gotcha
    });
}]);