2014-10-27 66 views
5

我正在使用一個非常簡單的攔截器來檢查響應拒絕403訪問被禁止將用戶重定向到登錄名,但它不重定向。我可以將console.log直到$ location.path之前的行,並且在它之後,它永遠不會發生。這事發生在別人身上過嗎?我一直在盯着這一點...原來我甚至不想使用$ location,但我不能注入ui.router而沒有獲得循環依賴,我也無法弄清楚擺脫這樣的位置應該讓我感動,而我想到了這一點。AngularJS重定向不在攔截器中發生

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

當你得到的$state實例'$ location.path'只有在未來消化週期旁邊會運行,因爲會發生路線變更聲明。你不可能直接注入'$ state',而是可以注入'$ injector'並獲得'$ injector.get('$ state')。go(statename)''。同時設置位置路徑或href等不會阻塞活動,這意味着它會讓當前腳本完全執行,然後更改位置。 – PSL 2014-10-27 19:06:05

+0

謝謝,注射$注射器的作品,我不知道非阻塞活動,所以再次感謝你:)你應該把它放到下面的答案中,這樣它就更加明顯,並且你得到更多的信用。再次感謝 – mtpultz 2014-10-27 20:11:53

+0

很高興它的作品。當然,我會放棄一個答案。 – PSL 2014-10-27 20:17:08

回答

2

當使用location.href它並立即設置位置和停止腳本的執行,但位置變化將是,只有當正在執行的當前腳本路徑完成有效的設置窗口位置。這就是爲什麼你看到下面的聲明得到執行。它也不是阻塞活動(不像警報或提示)。使用角度包裝設置位置時,它將在摘要循環後生效。在$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; 
}]); 
+0

我已經像你的代碼一樣遵循,但路由工作不正常。在網址成功路由,但視圖無法顯示。你能指導我嗎? – VjyV 2017-03-04 08:07:05