AngularJS,$消化错误试图重定向需要登录的网页应用程序 [英] AngularJS, $digest error trying to redirect application on pages requiring login
问题描述
我想重定向请求的状态需要登录的情况下AngularJS应用。这是我放在'运行'方法中对我的角度应用方法:
I'm trying to redirect an AngularJS app in the case that the requested state requires login. This is the method I've placed within the 'run' method on my angular app:
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
if(toState.data.requiresLogin && !User.isLoggedIn)
{
event.preventDefault();
$state.go('login');
}
});
看起来非常简单,但我得到这个错误消化。这似乎是由事件。preventDefault()语句来触发。我不能删除当然...
Seems straightforward, but I'm getting this digest error. It appears to be triggered by the event.preventDefault() statement. I can't remove that of course...
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [["fn: $locationWatch; newVal: 7; oldVal: 6"],["fn: $locationWatch; newVal: 8; oldVal: 7"],["fn: $locationWatch; newVal: 9; oldVal: 8"],["fn: $locationWatch; newVal: 10; oldVal: 9"],["fn: $locationWatch; newVal: 11; oldVal: 10"]]
...
这是如何重构这清除此错误,或有什么错误,即使手段有什么建议?
Any advice on how to refactor this to clear this error, or what the error even means?
推荐答案
有一个工作示例的,如何重定向登录。首先,定义了4种状态 - 其中2 要求 验证的,第三个是的公共的(任何人)的有同样的登录的状态:
There is a working example, how to redirect to login. Firstly there are 4 states defined - 2 of them require authentication, third is public (for anybody) and there is also login state:
$stateProvider
// available for anybody
.state('public',{
url : '/public',
template : '<div>public</div>',
})
// just for authenticated
.state('some',{
url : '/some',
template : '<div>some</div>',
data : {requiresLogin : true },
})
// just for authenticated
.state('other',{
url : '/other',
template : '<div>other</div>',
data : {requiresLogin : true },
})
// the log-on screen
.state('login',{
url : '/login',
templateUrl : 'tpl.login.html',
controller : 'UserCtrl',
})
和这将是 $ stateChangeStart
闪避,其中总是的重定向到登录
- 如果需要的话...只有登录
itslef和公共
可随时/任何人
and that would be the $stateChangeStart
def, which always redirects to login
- if required ... only login
itslef and public
are available always/to anybody
.run(['$rootScope', '$state', 'User', function($rootScope, $state, User)
{
$rootScope.$on('$stateChangeStart'
, function(event, toState, toParams, fromState, fromParams) {
var isAuthenticationRequired = toState.data
&& toState.data.requiresLogin
&& !User.isLoggedIn
;
if(isAuthenticationRequired)
{
event.preventDefault();
$state.go('login');
}
});
}])
检查所有行动 rel=\"nofollow\">
Check that all in action here
这篇关于AngularJS,$消化错误试图重定向需要登录的网页应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!