2017-06-09 85 views
1

我想實現的是如果會話超時從任何頁面我將用戶重定向到登錄頁面,我想顯示一些錯誤。現在我可以重定向,但錯誤部分不起作用。Angular:重定向到登錄頁面以及錯誤消息

這是我httpInterceptor

@app.service 'httpInterceptor', [ 
    '$window', 
    'AuthenticationService' 
    ($window, AuthenticationService) -> 
    { 
     responseError: (res) -> 
     if res.status == 403 
      AuthenticationService.error = true; 
      $window.location.href = '/' 
     res 
    } 
] 

,並在登錄控制器我想使用這項服務

@app.service 'AuthenticationService', -> 
    @error = false 
    return 

AuthenticationService.error但我仍然得到這個值設置爲false。

編輯JS代碼

this.app.service('httpInterceptor', [ 
    '$window', 
    'AuthenticationService', 
    ($window, AuthenticationService) => 
    ({ 
     responseError(res) { 
     if (res.status === 403) { 
      AuthenticationService.error = true; 
      $window.location.href = '/'; 
     } 
     return res; 
     } 
    }) 

]); 

服務

this.app.service('AuthenticationService', function() { 
    this.error = false; 
}); 
+0

這是什麼語言? CoffeeScript的?與角:) :)? – PierreDuc

+0

yes it coffeescript – Saad

+0

@PierreDuc我已添加JS代碼 – Saad

回答

0

使用$定位服務如果您正在使用locationRouter或者如果您使用stateProvider的看法改變使用$狀態服務。 $ location.path('/'); $ location.path('/'); $ location.path('/'); $ location.path('/'); $ state.go('/');

這將避免重置您爲錯誤消息設置的服務值。

this.app.service('httpInterceptor', [ 
    '$window', 
    'AuthenticationService','$location;, '$state', 
    ($window, AuthenticationService) => 
    ({ 
     responseError(res) { 
     if (res.status === 403) { 
      AuthenticationService.error = true; 
      //$window.location.href = '/'; // instead of this 
      // Use below 
      $state.go('/'); or $location.path('/'); 

     } 
     return res; 
     } 
    }) 

]); 
+0

不要忘記注入服務,因爲我在那裏做了。 –

+0

我已經嘗試過位置和狀態,它只是在不改變的情況下添加'#/',它不是一個單獨的頁面應用程序。也與$狀態我收到錯誤。 – Saad

0

當你做$window.location.href = '/';你的頁面有被重新加載,所以你設置爲服務一切刷新之後被清除。如果您不需要刷新頁面,請按照建議使用$location$state。如果您仍想重新加載頁面,則需要在頁面/狀態之間路徑信息。您可以使用localStorage或只需將查詢參數添加到網址.href = '/?authError=Y',然後在應用程序引導中讀取並清除它。

更新:根據你的意見,你需要重定向到另一個頁面,那不是角度頁面?如果是這樣,您既不能使用$location也不能使用$state,因爲角度不知道如何解決這些問題(您可以使用$location.href = "\",但與$window.location.href = '/';相同)。

P.S. cofeescript ...你是色狼:-P