2015-07-02 34 views
5

我有一个需要授权的状态。我听$stateChangeStart事件,如果toState.data.protected和用户没有授权,我打电话e.preventDefault()$state.go('login')

当我在根url中打开应用程序时,我会自动重定向到受保护的状态。 这会导致10 $摘要循环,并且当我在根网址中打开应用程序时,我最终处于登录状态,并且自动重定向到受保护状态。

Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!

看到这个plnkr:http://plnkr.co/edit/1voh7m?p=preview

我成功地使用类似的代码在不同的项目,角度1.2.26没有任何错误。

示例代码angular 1.4.1, ui.router 0.2.15

//config block 
$urlRouterProvider.otherwise('/main'); 
$stateProvider 
.state('main', { 
    url: '/main', 
    templateUrl: 'main.html', 
    controller: 'MainController as main', 
    data: {'protected': true} 
}) 
.state('login', { 
    url: '/login', 
    templateUrl: 'login.html', 
    controller: 'LoginController as login' 
}); 

// in a run block 
$rootScope.$on("$stateChangeStart", function (event, toState) { 
    if (!event.defaultPrevented && toState.data && 
      toState.data.protected) { 
     // the user is not authorized, do not switch to state 
     event.preventDefault(); 
     // go to login page 
     $state.go('login'); 
    } 
}); 

你知道是什么原因导致的循环?

我不知道的事情可能会发生这样的:

  1. 拦截main.submain状态
  2. 开始过渡到登录状态
  3. UI路由器过渡获取信息的第一transiotion了取消
  4. UI路由器运行$urlRouter.update()并开始过渡到main.submain

编辑:简化的状态配置。

+0

你在哪里定义什么数据被保护? – user3727843

+0

在主状态下使用状态定义:'data:{'protected':true}'。状态是原型继承的,所以main.submain状态具有相同的值。 – kvetis

+0

我很抱歉,我有一个不正确的plunk附件,没有证明这个问题。 – kvetis

回答

12

这是UI.Router的问题 - 在Github上查看此问题:https://github.com/angular-ui/ui-router/issues/600

基本上,如果你使用.otherwise('/main')(也指出了@Grundy),那么URL被改变/main当路径不能解决。在$locationChangeSuccess之后,我的听众被呼叫,我拒绝使用event.preventDefault()重定向。这会导致位置变回未知路径,从而导致再次使用回退路径。这会导致无限循环。解决的办法是这样的:

$urlRouterProvider.otherwise(function($injector) { 
    var $state = $injector.get('$state'); 
    $state.go('main'); 
}); 

你可以说出一个都会调用与$injector功能,你可以不回来的往复位置的改变重定向到您的主状态(或404)。 Thx给Github上的人,我应该在发布这个问题之前在那里搜索。

工作量:http://plnkr.co/edit/eQXaIk

+1

帮助,谢谢! – Rantiev

相关问题