【问题标题】:AngularJS UI-Router flickering during rerouteAngularJS UI-Router在重新路由期间闪烁
【发布时间】: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}
        })

【问题讨论】:

  • 您的“解决”会立即解决,因为 authenticatenotAuthenticate 函数都不会返回承诺。所以,在main状态的情况下,你成功进入状态,只是稍后被重定向到home
  • @NewDev 似乎$timeout 是问题所在,它从.catch 函数登陆页面并在下一个摘要中重定向..我不确定..
  • @NewDev 感谢新开发者。你的回答是正确的。如果你发布它,我会奖励你这个问题。

标签: javascript angularjs angular-ui-router


【解决方案1】:

状态的resolve 旨在在状态激活之前“解决”一些注射剂。因此,“resolves”(resolve: {...} 的属性)期望一个函数返回一个值或一个值的承诺。在身份验证的情况下,它可能是user

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

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

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

【讨论】:

    猜你喜欢
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 2016-05-25
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多