N
N
nuclear_kote2016-08-19 00:39:36
Angular
nuclear_kote, 2016-08-19 00:39:36

How to make $http.then be called 2nd time?

angular
.module('app', ['ngStorage'])
.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('TestInterceptor');
}])
.factory('TestInterceptor', ['$q', '$injector', '$localStorage', function ($q, $injector, $localStorage) {
    return {
    	request: request,
    	response: response,
    	responseError: responseError
    };

    function request(config) {
    	console.log('request');
    	config.test = !config.test;
    	if (config.test) {
    		config.timeout = 1;
    	}  else {
      config.timeout = 10000;
    	}
    	return config;
    }
    function response(resp) {
    	console.log('response');
    	console.log(resp);
    	if (resp.config.method == 'GET' ) {
    		if (!resp.config.cached) {
    			var restCache = $localStorage.cache;
      		if (restCache == null) {
      			restCache = {};
      		}
      		resp.cached = true;
    			restCache[resp.config.url] = angular.toJson(resp);
    			$localStorage.cache = restCache;
    			
    		}
    		
    	} 
    	return $q.resolve(resp);
    }
    
    function responseError(rej) {
    	console.log(' responseError(rej) {');
    	console.log(rej);
    	var defer = $q.defer();
    	var config = rej.config;
    	if (config.test) {
    			function success(response) {
                                       //с этого места success callback не дергается. 
          defer.resolve(response);
    			}
    			function errorCallback(reject) {
    				defer.reject(reject);
    			}
    			$http = $injector.get('$http');
    			$http(rej.config).then(success, errorCallback);
    }
    	if (config.method == 'GET' && (rej.status == 408 || rej.status <= 0) && config.test) {
      var restCache = $localStorage.cache;
      if (restCache != null && restCache[rej.config.url] != null ) {
                                //с этого места дергается sucess callback
        return $q.resolve(angular.fromJson(restCache[rej.config.url]));
      }
    	}
    	return $q.reject(rej);
    }
}])
.run(['$http', function ($http) {
  $http.get('http://example.com/service/').then(function (res) {
    console.log('res');
    console.log(res);
  });
}]);

Is it possible to pull then twice from the interceptor?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Philipp, 2016-08-19
@zoonman

Angular.JS has its own built-in query caching.
Read https://docs.angularjs.org/api/ng/service/$http and https://docs.angularjs.org/api/ng/service/$cacheFactory

angular
.module('app', ['ngStorage'])
.config(['$httpProvider', function ($httpProvider, $cacheFactory) {
    $httpProvider.defaults.cache = $cacheFactory('cacheId');
}])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question