Остановить запрос в перехватчике angularjs
Как я могу остановить запрос в перехватчике Angularjs.
Есть ли способ сделать это?
Я попытался использовать promises и отправил вместо этого решение reject!
.factory('connectionInterceptor', ['$q', '$timeout',
function($q, $timeout) {
var connectionInterceptor = {
request: function(config) {
var q = $q.defer();
$timeout(function() {
q.reject();
}, 2000)
return q.promise;
// return config;
}
}
return connectionInterceptor;
}
])
.config(function($httpProvider) {
$httpProvider.interceptors.push('connectionInterceptor');
});
Ответы
Ответ 1
У службы $http есть опции
тайм-аут для выполнения задания.
вы можете сделать так:
angular.module('myApp')
.factory('httpInterceptor', ['$q', '$location',function ($q, $location) {
var canceller = $q.defer();
return {
'request': function(config) {
// promise that should abort the request when resolved.
config.timeout = canceller.promise;
return config;
},
'response': function(response) {
return response;
},
'responseError': function(rejection) {
if (rejection.status === 401) {
canceller.resolve('Unauthorized');
$location.url('/user/signin');
}
if (rejection.status === 403) {
canceller.resolve('Forbidden');
$location.url('/');
}
return $q.reject(rejection);
}
};
}
])
//Http Intercpetor to check auth failures for xhr requests
.config(['$httpProvider',function($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
}]);
Ответ 2
В итоге я обошел вызов angular XHR со следующим angular Interceptor:
function HttpSessionExpiredInterceptor(sessionService) {
return {
request: function(config) {
if (sessionService.hasExpired()) {
/* Avoid any other XHR call. Trick angular into thinking it a GET request.
* This way the caching mechanism can kick in and bypass the XHR call.
* We return an empty response because, at this point, we do not care about the
* behaviour of the app. */
if (_.startsWith(config.url, '/your-app-base-path/')) {
config.method = 'GET';
config.cache = {
get: function() {
return null;
}
};
}
}
return config;
}
};
}
Таким образом, любой запрос, POST, PUT,... преобразуется как GET, так что механизм кэширования может быть
используется angular. На этом этапе вы можете использовать свой собственный механизм кэширования, в моем случае, когда сеанс
истекает, мне все равно, о чем вернуться.
Ответ 3
Не уверен, возможно ли вообще. Но вы можете начать $http-запрос с помощью "отмена".
Вот пример из этого ответа:
var canceler = $q.defer();
$http.get('/someUrl', {timeout: canceler.promise}).success(successCallback);
// later...
canceler.resolve(); // Aborts the $http request if it isn't finished.
Итак, если у вас есть контроль над тем, как вы начинаете свой запрос, это может быть вариант.
Ответ 4
Я только что вернулся как пустой объект
'request': function request(config) {
if(shouldCancelThisRequest){
return {};
}
return config;
}