一尘不染

$ on('$ stateChangeStart')中的UI路由器$ state.go造成无限循环

angularjs

我正在尝试将登录信息引入用户浏览应用程序的方式。

如果用户满足特定要求,我假装将用户重定向到该页面,直到他导航到登录页面之前

防止事件从$ stateChangeStart停止,阻止状态更改,如预期的那样,但是当我运行$
state.go(’into_somewhere’)时,我进入无限循环

我的角度版本是1.3.1,而ui-router是最新的

.factory('RouteHistory', function ($rootScope,$log, $state, Auth, $urlRouter, $timeout) {

    // after the user enter a page
    var currentState = '';

    // when the user is trying to access a page that he has not permissions
    // or that requires the user to be logged in
    var pendingState = '';

    var isMenuTogglerVisible = false;
    var skipFromStateVal = true;

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

      event.preventDefault();



      if (toState.name == 'login' && fromState.name != 'login'){
        $log.log('Ui-router: changing to login');
        // $urlRouter.sync();
        $state.go('login')
        //pendingState = fromState;
        //$log.log('Peding state updated to:' + pendingState.name );
        //$urlRouter.sync();
      }

      if (fromState.name == 'login' && Auth.isLoggedIn()) {
        $log.log('Ui-router: going from login');
        //$state.go(fromState.name);
        $timeout(function(){
          // $state.go('home', null, {/*reload: true, location: 'replace'*/});
          $state.go('browse-machine');
          //$urlRouter.sync();
        },2000)
      }



      $log.log({
        'toState': toState,
        'toParams': toParams,
        'fromState': fromState,
        'fromParams': fromParams
      })

    })


    return {

    };
  });

阅读 247

收藏
2020-07-04

共1个答案

一尘不染

一般来说,我 只在需要时才* 重定向 $state.go() 。在其他情况下,请退出事件监听器: *

if (toState.name === 'login' ){
  // doe she/he try to go to login? - let him/her go
  return;
}

if(Auth.isLoggedIn()){
   // is logged in? - can go anyhwere
   return;
}

// else
$state.go('login')

这是简化的逻辑,但表明,仅在需要时才应更改为执行。还有一些其他示例,其中包含更详细的实现方式和功能:

正如评论中所提供的,有一个plunker,我在这里像这样更改

...
// three new lines
if (toState.name === 'specialRoute'){
  return;
}

if (fromState.name=='route1'){
  event.preventDefault();
  $state.go('specialRoute')
}

而且这 不再
循环了。请在这里检查

2020-07-04