【问题标题】:AngularJS redirect not occurring in interceptorAngularJS重定向未发生在拦截器中
【发布时间】:2014-12-23 01:21:39
【问题描述】:

我正在使用一个非常简单的拦截器来检查 responseRejection 的 403 Access Forbidden 以将用户重定向到登录,但它不会重定向。我可以 console.log 一直到 $location.path 之前和之后的那一行,它永远不会发生。这事发生在别人身上过吗?我已经盯着这个看了一会儿...本来我什至不想使用$location,但是如果没有循环依赖,我就无法注入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.path 时,它旁边的语句将运行,因为路径更改只会在下一个摘要循环中发生。您可能无法直接注入$state,而是可以注入$injector 并获取$injector.get('$state').go(statename)。另外设置位置路径或href等不会阻塞活动,这意味着它将让当前脚本完全执行然后更改位置。
  • 谢谢,注入 $injector 有效,我不知道非阻塞活动,所以再次感谢你:) 你应该把它放到下面的答案中,这样它会更明显,你会得到更多的信任.再次感谢
  • 很高兴它有效。当然,我会放弃答案。

标签: angularjs angularjs-service angular-http-interceptors


【解决方案1】:

当使用location.href设置窗口位置时,它会立即设置位置并停止脚本的执行,但位置更改只有在当前正在执行的脚本路径完成后才会生效。这就是为什么你会看到下面的 href 语句被执行。它也不是阻塞活动(与警报或提示不同)。使用角度包装器设置位置时,它将在摘要循环后生效。在$http 拦截器中注入$state 时,您会遇到一个有效的循环依赖问题。为了克服这个问题,您可以使用$injector. 获取$state 的实例

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

【讨论】:

  • 我已经和你的代码一样,但是路由不能正常工作。在 url 中成功路由但视图无法显示。你能指导我吗?
猜你喜欢
  • 2013-03-11
  • 2014-05-24
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 2014-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多