Моя цель аннулировать запрос xhr, если последний имеет статус 401.угловой HttpInterceptor отменен тайм-аут обещание прерванный запрос
С кодом ниже я могу отменить следующий запрос, но если я пытаюсь сделать
в другой запрос (т.е. сделать логин) прерывается (это нужно, как canceller.reject (причина))
поток
1 установить родительский маршрут (аутентификации), чтобы проверить, если требуется Войти
2 установлен дочерний корень, который наследующий состояние аутентификации
3, когда приложение попадет в маршрут отменить запрос на статьи и показать модальный логин
(function() {
'use strict';
function Auth($http) {
return {
isLoggedIn: function() {
return $http.get('/api/auth/isloggedin');
},
signin: function(data) {
return $http.post('/api/auth/signin', data);
}
};
}
function loginModal($modal, $rootScope,$templateCache) {
function successCallback (data) {
console.log('success',data);
}
function errorCallback (data) {
console.log('fail',data);
}
return {
open : function(){
var modalInstance = $modal.open({
template: $templateCache.get('auth/templates/modal-login.html'),
controller: 'LoginModalController',
controllerAs: 'auth'
});
return modalInstance.result.then(successCallback).catch(errorCallback);
}
};
}
function HttpInterceptor($rootScope,$q) {
var canceller = $q.defer();
return {
'request': function(config) {
config.requestTimestamp = new Date().getTime();
config.timeout = canceller.promise;
return config;
},
'response': function(response) {
response.config.responseTimestamp = new Date().getTime();
return response;
},
'responseError': function(rejection) {
if (rejection.status === 401) {
$rootScope.$emit('no-auth', rejection);
canceller.resolve('Unauthorized');
}
return $q.reject(rejection);
}
};
}
angular.module('auth.services', [])
.factory('Auth', Auth)
.factory('HttpInterceptor', HttpInterceptor)
.factory('loginModal', loginModal);
})();
(function() {
'use strict';
angular.module('auth',
['auth.services','auth.controllers','auth.routes'])
.run(function($rootScope,loginModal,HAS_MODAL_LOGIN){
$rootScope.$on('no-auth', function(event, data) {
if(HAS_MODAL_LOGIN){
loginModal.open();
}
});
});
})();
(function() {
'use strict';
function config($stateProvider,$httpProvider) {
$stateProvider
.state('auth', {
abstract: true,
template: '<ui-view/>',
resolve:{
auth : function(Auth){
return Auth.isLoggedIn();
}
}
});
//Http Intercpetor to check auth failures for xhr requests
$httpProvider.interceptors.push('HttpInterceptor');
}
angular.module('auth.routes', [])
.config(config);
})();
(function() {
'use strict';
function config($stateProvider) {
$stateProvider
.state('auth.articles', {
url: '/articles',
templateUrl: 'articles/templates/index.html',
controller:'ArticlesController as articles',
resolve:{
articlesData : function(Articles){
return Articles.get();
}
}
});
}
angular.module('articles.routes', [])
.config(config);
})();
спасибо, что я только что видел этот учебник, но хочу показать модальный логин и отклонить запрос (если я найду способ :)), все в реальных статьях приложений получают статус 403, но ради этого. .... :) – Whisher
Тогда вы можете попытаться использовать право $ q в контроллере Auth для отправки отклонений. –