【问题标题】:$stateChangeStart - State-change not prevented$stateChangeStart - 未阻止状态更改
【发布时间】:2018-09-08 02:18:49
【问题描述】:

如果未经授权的用户尝试访问受限状态,则受限状态会在$state.go(fromState.name) 发回之前加载。似乎event.preventDefault(); 没有触发?

$rootScope.$on('$stateChangeStart', 
               function (event, toState, toParams, fromState, fromParams) {

    if (toState.name == 'app.admin' || toState.name == 'app.bonus') {
        AuthService.isAuthenticated().then(function (response) {
            if (!response) {
                event.preventDefault();
                $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
            } else {
                event.preventDefault();
                if ('data' in toState && 'authorizedRoles' in toState.data) {
                    var authorizedRoles = toState.data.authorizedRoles;
                    if (!AuthService.isAuthorized(authorizedRoles)) {
                        $state.go(fromState.name, {}, {
                            reload: true
                        });
                        $rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
                    }
                }
            }
        }, function () {
            event.preventDefault();
            $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
        });
    }
});

【问题讨论】:

    标签: angularjs angular-ui-router


    【解决方案1】:

    您正在从异步回调中调用event.preventDefault()。所以,在它被调用的时候,事件监听函数已经返回,并且由于事件没有被阻止,路由器已经导航到下一个状态。

    如果你这样做,它会起作用

    $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
        if ((toState.name == 'app.admin' || toState.name == 'app.bonus')
            && !AuthService.isAuthenticated()) {
            event.preventDefault();
        }
    }
    

    当然,这意味着您的服务需要同步返回布尔值,而不是承诺。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 2021-04-06
      • 1970-01-01
      • 2015-05-16
      • 2021-01-27
      • 2015-03-18
      • 2016-06-05
      • 2020-06-15
      相关资源
      最近更新 更多