2016-07-21 14 views
0

私はトークンが要件と一致しない場合、場所の変更を防止しようとしています。(ルート|場所)ChangeStart preventDefault

.run(['$location','$rootScope','$http', 
    function($location, $rootScope, $http) 
    { 
    $rootScope.$on('$routeChangeStart', function(event, next){ 
     var nextPath = next.$$route.originalPath; 
     if (nextPath != '/login'){ 
     var token = localStorage.getItem('token'); 
     $http({ 
      method: 'GET', 
      url: '/token', 
      headers: { 
      'auth-token': token 
      } 
     }).then(function(data){ 
      $location.url(nextPath); 
     }, function(err){ 
      event.preventDefault(); //can't prevent here 
      // $location.path('/login'); //this works perfectly but couse unneeded location change 
     }) 
     } 
    }) 
}]) 

変更がlocationChangeStartでもrouteChangeStart

でどちらも防ぐことができない場所

答えて

0
var isLoginVerified = false; 

$rootScope.$on('$routeChangeStart', function(e, next){ 
    var nextPath = next.$$route.originalPath; 

    if (nextPath != '/login'){ 
    var token = localStorage.getItem('token') || ''; 

    if (!isLoginVerified) 
     e.preventDefault(); 

    $http({ 
     method: 'GET', 
     url: '/token', 
     headers: { 
     'auth-token': token 
     } 
    }).then(function(data){ 
     isLoginVerified = true; 
     $location.path(nextPath) 
     }, 
     function(err){ 
     isLoginVerified = false; 
     $location.path('/login'); 
     }); 
    } 
}); 

isLoginVerifiedフラグを追加する魔法

を作る:私は私が .run段階で使う簡単なコードを、持っています
関連する問題