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

标签 javascript angularjs angular-ui-router

我有 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/

相关文章:

javascript - 将再生器运行时与 NodeJS 结合使用

jquery - 大型幻灯片/画廊固定高度

javascript - ng-show 和 localStorage 表现异常

node.js - 如何从数据库动态添加路由到angularjs

javascript - $编译:ctreq error in angular code

javascript - 给定代码中 <svg> 和 <canvas> 实现有什么区别?

javascript - 将 javascript 值插入表单字段

angularjs - 使用 Angular 的 ui-router 掌握详细信息

javascript - 有哪些方法可以降低 Angular Controller 的复杂性(使用 ui-router)?

javascript - 路由时在配置中的 templateUrl 上应用条件