2015-09-12 169 views
0

我有AngularJS ui-router,並且正在檢查狀態更改期間的身份驗證狀態。在此次更改期間,由於AngularJS解決了是否應呈現該頁面的承諾,我正在經歷閃爍。例如,如果用戶登錄,/#/被保護並重定向到/#/ home。但是,我看到/#/的html的簡短瞥見,然後發生重定向。我怎樣才能阻止這種閃爍發生?在重新路由期間AngularJS UI路由器閃爍

function authenticate($q, $state, $timeout, AuthService) { 
    AuthService.isLoggedIn() 
     .then(function() { 
      // Resolve the promise successfully 
      console.log("auth") 
      return $q.when() 
     }) 
     .catch(function() { 

      $timeout(function() { 
       // This code runs after the authentication promise has been rejected. 
       // Go to the log-in page 
       $state.go('main') 
      }) 

      // Reject the authentication promise to prevent the state from loading 
      return $q.reject() 
     }) 


} 

function notAuthenticate($q, $state, $timeout, AuthService) { 
    AuthService.shouldNotBeLoggedIn() 
     .then(function() { 
      // Resolve the promise successfully 
      console.log("not auth") 
      return $q.when() 

     }).catch(function() { 

      $timeout(function() { 
       // This code runs after the authentication promise has been rejected. 
       // Go to the log-in page 
       $state.go('home') 
      }) 
      // Reject the authentication promise to prevent the state from loading 
      return $q.reject() 

     }) 

} 

/** @ngInject */ 
function routeConfig($stateProvider, $urlRouterProvider) { 
    $stateProvider 
     .state('home', { 
      url: '/home', 
      templateUrl: 'app/home/home.html', 
      controller: 'HomeController', 
      controllerAs: 'home', 
      resolve: {authenticate: authenticate} 
     }) 

     .state('main', { 
      url: '/', 
      templateUrl: 'app/main/main.html', 
      controller: 'MainController', 
      controllerAs: 'main', 
      resolve: {notAuthenticate: notAuthenticate} 
     }) 
+2

您的「解決」立即解決,因爲'authenticate'和'notAuthenticate'函數都不會返回承諾。所以,如果處於'main'狀態,你就成功進入狀態,只是稍後重定向到'home' –

+0

@NewDev好像'$ timeout'就是問題所在,它從'登陸頁面。趕上'功能和重新定向在下一個摘要..我不知道.. –

+0

@NewDev謝謝新的開發。你的回答是正確的。如果你發佈它,我會給你這個問題。 – user3839821

回答

2

狀態的resolve是爲了「解決」一些注射劑,狀態被激活之前。因此,「解決方案」(resolve: {...}的屬性)預期會返回一個值或一個值的承諾。在身份驗證的情況下,它可能是user

在你的情況下,解析函數沒有return一個承諾 - 他們只是立即運行並完成,從而激活狀態。然後,一些(短)時間後,你的AuthService踢,並決定改變狀態。這會導致閃爍。

function authenticate($q, $state, $timeout, AuthService) { 

    // this "return" is what returns the promise 
    return AuthService.isLoggedIn() 
        .then(....); 
}