在$on(‘$stateChangeStart’)中,有一个无限循环的angularjs – Ui-Router $state.go

前端之家收集整理的这篇文章主要介绍了在$on(‘$stateChangeStart’)中,有一个无限循环的angularjs – Ui-Router $state.go前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试以用户浏览应用程序的方式引入登录.

如果该页面符合特定要求,我假装将用户重定向到他之前的页面,然后他导航到登录页面

阻止$stateChangeStart stop的事件像预期的状态改变,但是当我运行$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 {

    };
  });
一般我会说,让我们重定向($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')

这是简化的逻辑,但是显示,只有在需要时才应该改为执行.还有一些其他的例子,更详细的实现和空格:

> Confusing $locationChangeSuccess and $stateChangeStart
> Angular UI Router: nested states for home to differentiate logged in and logged out
> other example of log in
> angular ui-router login authentication

根据评论中提供的,有plunker,我改变了这样here

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

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

这不是循环了.请检查here

原文链接:https://www.f2er.com/angularjs/142629.html

猜你在找的Angularjs相关文章