2016-10-25 32 views
0

如果用户没有登录,我想阻止状态改变。我使用下面的代码,工作正常。角度防止状态改变用户不能登录

angular.module('app', [...]) 
     .config(function(){}) 
     .run(function($rootscope,$auth,$state){ 

     $rootScope.$on("$stateChangeStart", function(event){ 
     var user = $auth.getToken(); 
     if (user === null){ 
      // User isn’t authenticated 
      $state.transitionTo("index"); 
      event.preventDefault(); 
     } 
     }); 

     }) 

但显示此错误!

angular.js:12783 RangeError: Maximum call stack size exceeded 
at Array.indexOf (native) 
at indexOf (http://localhost:9000/bower_components/angular-ui-router/release/angular-ui-router.js:87:18) 
at http://localhost:9000/bower_components/angular-ui-router/release/angular-ui-router.js:1708:46 
at forEach (http://localhost:9000/bower_components/angular/angular.js:341:20) 
at http://localhost:9000/bower_components/angular-ui-router/release/angular-ui-router.js:1707:9 
at forEach (http://localhost:9000/bower_components/angular/angular.js:341:20) 
at Object.$$keys (http://localhost:9000/bower_components/angular-ui-router/release/angular-ui-router.js:1706:7) 
at Object.$$validate [as $$validates] (http://localhost:9000/bower_components/angular-ui-router/release/angular-ui-router.js:1729:23) 
at Object.transitionTo (http://localhost:9000/bower_components/angular-ui-router/release/angular-ui-router.js:3184:27) 
at http://localhost:9000/scripts/app.js:114:24 

任何人都可以帮助我吗?

回答

0

你能试试吗?并让我知道。

angular.module('app', [...]) 
     .config(function(){}) 
     .run(function($rootscope,$auth,$state){ 

     $rootScope.$on("$stateChangeStart", function(event){ 
     var user = $auth.getToken(); 
     if (user === undefined){ 
      // User isn’t authenticated 
      $state.transitionTo("index"); 
      event.preventDefault(); 
     } 
     }); 

     }) 
1

你的stateChangeStart函数创建一个循环,这就是为什么你会收到错误。试想一下:

  1. 国家开始变化
  2. 用户没有通过验证
  3. 国家去“索引”
  4. 国家开始变化
  5. 用户没有通过验证
  6. 国家去“索引”

你可以尝试使用一些只用于身份验证的状态变量用户,例如:

$rootScope.$on("$stateChangeStart", function(event, toState){ 
    if (toState.auth) { 
     var user = $auth.getToken(); 

     if (!user) { 
     // User isn’t authenticated 
     event.preventDefault(); 
     $state.transitionTo("index"); 
    } 
    } 
    }); 
+0

总是返回true?!!!!! –