2016-10-25 30 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?!!!!! –