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

mtp*_*ltz 5 angularjs angularjs-service angular-http-interceptors

我正在使用一个非常简单的拦截器来检查响应拒绝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;
}])
Run Code Online (Sandbox Code Playgroud)

PSL*_*PSL 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;
}]);
Run Code Online (Sandbox Code Playgroud)