在一个 Web 应用程序中,我希望当用户在 $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;
}
});