简体   繁体   中英

How to reuse HTTP request with retry logic in AngularJS

Is it possible to execute the same HTTP request more than once in AngularJS? ie without re-defining the same request twice?

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

The previous answer is good in terms of reusing it as service. But it looks like you really want to abstract out the retry logic as well. Here is how i would do that.

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');
    });
  }
}]);

And just inject SessionService anywhere say in yourcontroller:-

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

Plnkr

It's what services and factories were made for:

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

Inject and use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM