gpt4 book ai didi

AngularJS重定向未发生在拦截器中

转载 作者:行者123 更新时间:2023-12-04 21:14:46 24 4
gpt4 key购买 nike

我正在使用一个非常简单的拦截器来检查 403 Access Forbidden 的 responseRejection 以将用户重定向到登录名,但它不会重定向。我可以 console.log 一直到 $location.path 之前和之后的那一行,它永远不会发生。这事发生在别人身上过吗?我已经盯着这个看了一会儿...本来我什至不想使用$location,但是如果没有循环依赖,我就无法注入(inject)ui.router,我也不知道如何摆脱如此 $location 应该让我继续前进,而我却在想它。

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

最佳答案

使用 location.href 设置窗口位置时它确实会立即设置位置并停止脚本的执行,但位置更改只有在当前正在执行的脚本路径完成后才会生效。这就是为什么你会看到下面的 href 语句被执行。它也不是阻塞事件(与警报或提示不同)。使用 Angular 包装器设置位置时,它将在摘要循环后生效。在注入(inject) $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;
}]);

关于AngularJS重定向未发生在拦截器中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26594763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com