【问题标题】:AngularJS on $stateChangeStart loop$stateChangeStart 循环上的 AngularJS
【发布时间】:2016-04-17 15:58:36
【问题描述】:

在我想要的网络应用程序中,当用户在 $state 中路由时,Angular 会检查是否有令牌以及他是否有权限。但我有一个问题:即使我执行 event.preventDefault(),它也会启动一个循环并且浏览器崩溃。我怎样才能防止这个循环,让用户去或阻止导航?

代码:

  .run(function ($rootScope, $window, $state, Auth) {
  $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, $window) {

// Easy case that doesn't loop: just 'return'
if (toState.name === 'login' ){
    // doe she/he try to go to login? - let him/her go
    return;
}

if (Auth.isLoggedIn && $window.localStorage.identityToken) {

  var requiredAdmin = toState.data.requiredAdmin; 
  if (requiredAdmin && $window.localStorage.isAdmin){
    $state.go(toState.name); // it starts the loop
  } else { // if he is logged but has no permission, stop the navigation
    $state.go(fromState.name); // it starts the loop
  }

  return;
}

});

【问题讨论】:

    标签: angularjs angular-ui-router single-page-application angularjs-rootscope


    【解决方案1】:

    您应该检查更高的状态,而不是每次状态更改,因此如果您有 /login、/secured、/secured/.... 等路由,请检查 /secured 状态的 resolve 子句否则您的逻辑将在每次状态更改时执行,这不是身份验证/授权过程的正确方法。

    https://github.com/angular-ui/ui-router/wiki.

    这样您只在子路径上进行一次检查。

    【讨论】:

    • 谢谢,我已经尝试了一个承诺 - 方法!这是代码:jsfiddle.net/tzhxok68/2 但控制台显示此错误:无法设置未定义的属性“承诺”
    • 当定义路由时,状态定义通过 $stateProvider.state 发生在配置块上
    猜你喜欢
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 2016-06-03
    相关资源
    最近更新 更多