Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了AngularJS重定向不在拦截器中发生大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用一个非常简单的拦截器来检查响应拒绝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;
}]);

大佬总结

以上是大佬教程为你收集整理的AngularJS重定向不在拦截器中发生全部内容,希望文章能够帮你解决AngularJS重定向不在拦截器中发生所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: