How to reuse an HTTP request with retry logic in AngularJS

Is it possible to execute the same HTTP request more than once in AngularJS? that is, without re-defining the same query 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
source share
2 answers

What services and plants were created for:

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

Input and use

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

The previous answer is good in terms of reusing it as a service. But it looks like you really want to ignore the logic of repetition. This is how I do it.

 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 add a SessionService anywhere in your controller: -

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

Plnkr

+4
source

Source: https://habr.com/ru/post/1201189/


All Articles