AngularJS UI-Router在重新路由期间闪烁

时间:2015-09-12 07:41:38

标签: javascript angularjs angular-ui-router

我有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}
        })

1 个答案:

答案 0 :(得分:2)

该州的resolve旨在“解决”问题。一些注射剂,在状态被激活之前。所以,"解决了#34; (resolve: {...})的属性期望一个函数返回一个值或一个值的promise。在身份验证的情况下,它可以是user

在您的情况下,解析函数不会return一个承诺 - 它们只是立即运行并完成,从而激活状态。然后,稍后(短)时间,你的AuthService开始并决定改变状态。这会导致闪烁。

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

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