2015-09-12 156 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(....); 
}