我正在使用一个非常简单的拦截器来检查403Revidden的响应拒绝将用户重定向到登录,但它没有重定向。我可以将console.log直接放到$ location.path之前和之后的行,并且它永远不会发生。这事发生在别人身上过吗?我一直在盯着这个...原来我甚至不想使用$ location,但我不能注入ui.router而没有获得循环依赖,我也无法弄清楚如何摆脱这么多的位置应该让我感动,而我想到了。
.factory('AuthInterceptor', ['$q', '$location',
function( $q, $location ) {
var service = {
responseError: function( responseRejection ) {
// Authorization issue, access forbidden
if( responseRejection.status === 403 ) {
// TODO: show a login dialog, and/or redirect to login
console.log("Response rejected. Redirecting to login...");
$location.path('/login');
$location.replace();
console.log("Not so much with the redirecting... I'm still here");
}
// Propagate error to any chained promise handlers
return $q.reject( responseRejection );
}
}
return service;
}])
答案 0 :(得分:2)
使用location.href
设置窗口位置时,它会立即设置位置并停止执行脚本,但只有当正在执行的当前脚本路径完成时,位置更改才会生效。这就是为什么你看到href下面的语句被执行。它也不是阻止活动(与警报或提示不同)。使用角度包装器设置位置时,它将在消化循环后生效。在$state
拦截器中注入$http
时,您有一个有效的循环依赖问题。为了解决这个问题,您可以使用$state
$injector.
的实例
.factory('AuthInterceptor', ['$q', '$injector',
function( $q, $injector ) {
var $state;
var service = {
responseError: function( responseRejection ) {
// Authorization issue, access forbidden
if( responseRejection.status === 403 ) {
// TODO: show a login dialog, and/or redirect to login
console.log("Response rejected. Redirecting to login...");
_setState('login');
console.log("Not so much with the redirecting... I'm still here");
}
// Propagate error to any chained promise handlers
return $q.reject( responseRejection );
}
}
function _setState(stateName){
if(!$state) {
$injector.get('$state'); //Or just get $state from $injector always it is anyways the dependency container and service are singletons
}
$state.go(stateName);
}
return service;
}]);