【发布时间】:2015-09-12 07:41:37
【问题描述】:
我有 AngularJS ui-router,并在状态更改期间检查身份验证状态。在此更改期间,我遇到了闪烁,因为 AngularJS 解决了它是否应该呈现该页面的承诺。例如,如果用户登录,/#/ 将受到保护并重定向到 /#/home。但是,我看到 /#/ 的 html 的简要一瞥,然后重定向发生。如何阻止这种闪烁的发生?
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}
})
【问题讨论】:
-
您的“解决”会立即解决,因为
authenticate和notAuthenticate函数都不会返回承诺。所以,在main状态的情况下,你成功进入状态,只是稍后被重定向到home -
@NewDev 似乎
$timeout是问题所在,它从.catch函数登陆页面并在下一个摘要中重定向..我不确定.. -
@NewDev 感谢新开发者。你的回答是正确的。如果你发布它,我会奖励你这个问题。
标签: javascript angularjs angular-ui-router