2016-07-26 71 views
0

我正在編寫攔截器重定向到登錄頁面,如果用戶尚未登錄。我正在使用$位置來更改瀏覽器地址。

代碼工作,但是,「有時」,如果鍵入一個URL這是爲登錄用戶(例如:http://localhost:4662/#/index/companies),瀏覽器加載「企業」模板,並更改URL地址到登錄頁面:(http://localhost:4662/#/)。所以我必須點擊Enter才能真正重定向到登錄頁面。它有時會發生(有時也意味着我可以多次做,我得到的行爲預期,但突然就沒有盡本分)

這是我的代碼:

$httpProvider.interceptors.push(function ($q, $rootScope, $location, $injector) { 

     return { 
      request: function (config) { 

       //the same config/modified config/a new config needs to be returned. 
       var applicationService = $injector.get('applicationService'); 

       var loggedIn = applicationService.isLoggedIn(); 
       if (!loggedIn) { 
        $location.path('/'); 
        //$window.location.href = "#"; 
       } else if ($location.path() == '/') { 
        $location.path('/index');      
        } 

       return config; 
      }, 
      requestError: function (rejection) {...... 

而不是使用攔截我試了實施路線改變聽者如下,但我得到了一模一樣的問題:

app.run(function($rootScope, $state, $location, applicationService){ 
     $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){ 
      var loggedIn = applicationService.isLoggedIn(); 
      if (!loggedIn) { 
       $location.path('/');      
      } else if (toState.name == 'home') { 
       $location.path('/index'); 
      } 
     }); 
    }); 

我在做什麼錯?我想知道$ location是不是正確的選擇。

回答

1

通常使用的UI路由器,當你使用$state對象的go方法改變狀態programmaticly:

$state.go(to [, toParams] [, options]) 

便捷方法轉換到新的狀態。 $ state.go在內部調用$ state.transitionTo,但自動將選項設置爲{location:true,inherit:true,relative:$ state。$ current,notify:true}。這使您可以輕鬆地使用絕對或相對路徑,並指定唯一的參數,你想更新(而讓未指定的參數從當前狀態繼承。

https://github.com/angular-ui/ui-router/wiki/Quick-Reference#stategoto--toparams--options

+0

$ state.go了另一枚$ stateChangeStart事件,它在一個無限循環結束 –

+0

看看這個答案:http://stackoverflow.com/questions/20094273/stop-angular-ui-路由器導航,直到-承諾,是分辨/ 28827077#288 27077雖然我建議閱讀整個問題和所有答案。 – iH8

+0

謝謝,我發現event.preventDefault()避免了無限循環,並與$ state.go結合產生了預期的行爲。 –

0

終於找到了解決方案:

app.run(function($rootScope, $state, $location, applicationService){ 
     $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){ 
      var loggedIn = applicationService.isLoggedIn(); 

      //Go to home butis logged, redirect to main page (connections) 
      if (toState.name == 'home' && loggedIn) { 
       event.preventDefault(); 
       $state.go('index'); 
       return; 
      } 

      if (toState.name === 'home') { 
       // doe she/he try to go to login? - let him/her go 
       return; 
      } 

      if (loggedIn) { 
       // is logged in? - can go anyhwere 
       return; 
      } 

      // else, is logged in? No- Go to login 
      event.preventDefault(); 
      $state.go('home'); 


     }); 
    });