我有 AngularJS ui-router,并且正在状态更改期间检查身份验证的状态。在此更改期间,当 AngularJS 解析是否应显示该页面的 promise 时,我遇到了闪烁。例如,如果用户登录,/#/受到保护并重定向到/#/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}
})
最佳答案
状态的resolve
旨在在状态激活之前“解析”一些可注入(inject)的内容。因此,“resolves”(resolve: {...}
的属性)期望一个函数返回一个值或一个值的 promise 。在身份验证的情况下,它可能是用户
。
在您的情况下,解析函数不会返回
promise - 它们只是立即运行并完成,从而激活状态。然后,一段(短)时间后,您的 AuthService
启动并决定更改状态。这会导致闪烁。
function authenticate($q, $state, $timeout, AuthService) {
// this "return" is what returns the promise
return AuthService.isLoggedIn()
.then(....);
}
关于javascript - AngularJS UI-Router 在重新路由期间闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32536434/