AngularJS重定向不在拦截器中发生
发布时间:2020-12-17 06:47:25 所属栏目:安全 来源:网络整理
导读:我正在使用一个非常简单的拦截器来检查响应拒绝403 Access Forbidden将用户重定向到登录,但它没有重定向.我可以将console.log直接放到$location.path之前和之后的行,并且它永远不会发生.这事发生在别人身上过吗?我一直在盯着这个…原来我甚至不想使用$locat
我正在使用一个非常简单的拦截器来检查响应拒绝403 Access Forbidden将用户重定向到登录,但它没有重定向.我可以将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; }]) 解决方法
使用location.href设置窗口位置时,它会立即设置位置并停止执行脚本,但只有当正在执行的当前脚本路径完成时,位置更改才会生效.这就是为什么你看到href下面的语句被执行.它也不是阻止活动(与警报或提示不同).使用角度包装器设置位置时,它将在消化循环后生效.当你在$http拦截器中注入$state时,你有一个有效的循环依赖问题.为了克服这个问题,你可以使用$injector来获取$state的实例.
.factory('AuthInterceptor','$injector',$injector ) { var $state; var service = { responseError: function( responseRejection ) { // Authorization issue,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; }]); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |