(route | location)ChangeStart preventDefault

时间:2016-07-21 17:59:10

标签: angularjs

好的,如果令牌不符合要求,我会尝试阻止位置更改。我有简单的代码,我在.run阶段使用:

.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都无法阻止位置更改

1 个答案:

答案 0 :(得分: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标志会产生魔力