Kohjah Breese
Kohjah Breese

Reputation: 4136

How to reuse HTTP request with retry logic in AngularJS

Is it possible to execute the same HTTP request more than once in AngularJS? i.e. 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;
});

Upvotes: 1

Views: 3085

Answers (2)

PSL
PSL

Reputation: 123739

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

Upvotes: 4

tymeJV
tymeJV

Reputation: 104775

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

Upvotes: 2

Related Questions