nuclear_kote
@nuclear_kote

Как заставить $http.then вызваться 2й раз?

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


Возможно ли дернуть then дважды из interceptor'а?
  • Вопрос задан
  • 114 просмотров
Пригласить эксперта
Ответы на вопрос 1
zoonman
@zoonman
⋆⋆⋆⋆⋆
У Angular.JS есть свое встроенное кэширование запросов.
Читайте https://docs.angularjs.org/api/ng/service/$http и https://docs.angularjs.org/api/ng/service/$cacheFactory

angular
.module('app', ['ngStorage'])
.config(['$httpProvider', function ($httpProvider, $cacheFactory) {
    $httpProvider.defaults.cache = $cacheFactory('cacheId');
}])
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы