angularjs - locationChangeStart 和防止路线改变

标签 angularjs authentication url-redirection angularjs-routing angularjs-authentication

我正在尝试创建基本验证用户是否可以访问某些路线。
我在这方面取得了进展,但有一件事我无法弄清楚。

我正在使用 $locationChangeStart 来监控路线变化。场景是:
1. 如果用户已登录,则允许他访问所有路由,除了 auth 路由(登录、注册)。我正在通过从我的 AuthFactory 调用方法 isAuthenticated() 来检查这个
2. 如果用户没有登录,那么他只能访问登录和注册路由。应该阻止任何其他路由,并且在这种情况下应该将用户重定向到登录。

$rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl){
  if(AuthFactory.isAuthenticated()){
    if(AuthFactory.isAuthRoute(newUrl)){
      event.preventDefault();
      $location.path('/');
    }
  } else {
    if(!AuthFactory.isAuthRoute(newUrl)){
      event.preventDefault();
      $location.path('/login');
    }

  }
});

困扰我的是 preventDefault() 。如果应用程序使用 preventDefault() 到达代码,location.path()在那之后,根本行不通。

但是,如果我删除 event.preventDefault() , location.path()作品。这个问题是我需要防止,以防未登录的尝试访问某些非身份验证页面。

基本上,我希望能够根据请求的路线阻止或重定向。这样做的正确方法是什么?

最佳答案

好的,你需要这样做:

var authPreventer = $rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl){
    if(AuthFactory.isAuthenticated()){
        if(AuthFactory.isAuthRoute(newUrl)){
            event.preventDefault();
            authPreventer(); //Stop listening for location changes
            $location.path('/');
        }
    } 
    else {
        if(!AuthFactory.isAuthRoute(newUrl)){
            event.preventDefault();
            authPreventer(); //Stop listening for location changes
            $location.path('/login');
        }
    }
});

关于angularjs - locationChangeStart 和防止路线改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20772659/

相关文章:

javascript - AngularJS 出错

javascript - 向 Yeoman 创建的 AngularJS 应用程序中的所有请求添加 header

angularjs - 如何使用 angularjs 指令中的单击事件获取 TreeView 的选定节点值

cocoa - 如何在我的安全首选项 Pane 中创建锁定/解锁按钮和行为?

apache - 重定向到另一台主机时使用 [L] 标志

javascript - Protractor by.repeater 命令中是否存在错误

javascript - 谷歌登录 : Permission denied to generate login hint for target domain (javascript web app)

redirect - 将子域指向 github 页面

python - Request.Response 对象不会重定向到正确的 URL

php - MYSQL : Two tables "Signup" and "Login" ? 做成一个表好还是两个不同的表好