angularjs - (route | location)ChangeStart preventDefault -


ok, i'm trying prevent location change if token doesn't match requirements. have simple code, use in .run stage:

.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 couse unneeded location change         })       }     }) }]) 

location change can't prevented neither locationchangestart nor routechangestart

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');       });   } }); 

adding isloginverified flag make magic


Comments