基本的想法是使用Http响应拦截器重定向我的网页,如果它提供401状态。但我不知道我这样做是否正确:我以为是这样的,但我似乎比看上去更难。现在我发现了一个循环依赖关系。
我需要把拦截器推到别的地方吗?拦截器怎么知道我是否收到401请求。是否也可以定义哪些401需要被拦截,哪些被忽略。
(function () {
'use strict';
angular
.module('app', ['ngRoute','ngCookies','ngMessages'])
.config(routeConfig);
routeConfig.$inject = ['$routeProvider','$httpProvider'];
function routeConfig($routeProvider,$httpProvider) {
$routeProvider
.when('/', {
templateUrl: 'login.html',
controller : 'LoginController'
})
.when('/register', {
templateUrl: 'register.html',
controller : 'RegisterController'
})
.when('/main', {
//This gives an 401 status when the user has not been logged in
templateUrl: 'home.html',
controller : 'HomeController'
})
.otherwise('/');
// We need to add this for csrf protection
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
//this gives an Circular dependency error
$httpProvider.interceptors.push('HttpResponseInterceptor');
}
})();这是我的服务:
(function () {
'use strict';
angular
.module('app')
.factory('HttpResponseInterceptor', HttpResponseInterceptor);
HttpResponseInterceptor.$inject = ['$rootScope','$http','$q','$location'];
function HttpResponseInterceptor($rootScope,$http,$q,$location) {
return {
response: function(response){
if (response.status === 401) {
}
return response || $q.when(response);
},
responseError: function(rejection) {
if (rejection.status === 401) {
$location.path('/login');
}
return $q.reject(rejection);
}
};
}
})();Update2
正如评论中提到的那样,我正在注入很多东西。因此,这是一个修复的问题,但是现在当我转到登录页面时,它会在加载页面(localhost:8080/user)时发出请求,这会导致无限循环的重定向到登录页面,并导致浏览器崩溃。
那么有什么方法可以告诉阻断器哪些url需要重定向哪些不需要
发布于 2015-10-08 16:19:26
这是第二个问题的答案..。
查询拒绝对象并向IF语句添加一些进一步的条件.
你可以用.
Console.log(JSON.stringify(排斥));
然后添加条件到你的如果..。
if (rejection.status === 401 && rejection.config.url !== "/url/you/do/not/want/to/change/state/on") {
// do state.go or something else here
}发布于 2015-10-08 15:47:34
使用$injector注入服务有帮助吗?
(function () {
'use strict';
angular
.module('admin')
.factory('HttpInterceptor', httpInterceptor);
httpInterceptor.$inject = [
'$q', // return promises
'$injector' // login service injection
];
function httpInterceptor(q, injector) {
return {
responseError: function (rejection) {
var url = rejection.config ? rejection.config.url : undefined;
var state = injector.get("$state");
if (rejection.status === 401) {
if (!(url === "/api/logout" || state.current.name === "login" && url === "/api/authenticated")) {
var loginService = injector.get('LoginService');
loginService.logout();
}
}
if (rejection.status === 403) {
state.go("home");
}
return q.reject(rejection);
}
};
}
}());https://stackoverflow.com/questions/33019973
复制相似问题