How to reuse HTTP request with retry logic in AngularJS

半世苍凉 提交于 2019-12-11 12:11:30

问题


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

回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/25438396/how-to-reuse-http-request-with-retry-logic-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!