根据条件重定向到某个路由

根据条件重定向到某个路由

本文介绍了根据条件重定向到某个路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个具有登录视图和主视图的小型 AngularJS 应用程序,配置如下:

I'm writing a small AngularJS app that has a login view and a main view, configured like so:

$routeProvider
 .when('/main' , {templateUrl: 'partials/main.html',  controller: MainController})
 .when('/login', {templateUrl: 'partials/login.html', controller: LoginController})
 .otherwise({redirectTo: '/login'});

我的 LoginController 检查用户/密码组合并在 $rootScope 上设置一个属性来反映这一点:

My LoginController checks the user/pass combination and sets a property on the $rootScope reflecting this:

function LoginController($scope, $location, $rootScope) {
 $scope.attemptLogin = function() {
   if ( $scope.username == $scope.password ) { // test
        $rootScope.loggedUser = $scope.username;
        $location.path( "/main" );
    } else {
        $scope.loginError = "Invalid user/pass.";
    }
}

一切正常,但如果我访问 http://localhost/#/main,我最终会绕过登录屏幕.我想写一些类似每当路由改变时,如果 $rootScope.loggedUser 为空然后重定向到/login"

Everything works, but if I access http://localhost/#/main I end up bypassing the login screen. I wanted to write something like "whenever the route changes, if $rootScope.loggedUser is null then redirect to /login"

...

……等等.我可以以某种方式收听路线变化吗?无论如何我都会发布这个问题并继续寻找.

... wait. Can I listen to route changes somehow? I'll post this question anyway and keep looking.

推荐答案

经过一些文档和源代码的深入研究后,我想我已经开始工作了.也许这对其他人有用?

After some diving through some documentation and source code, I think I got it working. Perhaps this will be useful for someone else?

我在模块配置中添加了以下内容:

I added the following to my module configuration:

angular.module(...)
 .config( ['$routeProvider', function($routeProvider) {...}] )
 .run( function($rootScope, $location) {

    // register listener to watch route changes
    $rootScope.$on( "$routeChangeStart", function(event, next, current) {
      if ( $rootScope.loggedUser == null ) {
        // no logged user, we should be going to #login
        if ( next.templateUrl != "partials/login.html" ) {
          // not going to #login, we should redirect now
          $location.path( "/login" );
        }
      }
    });
 })

一件看起来很奇怪的事情是我必须测试部分名称 (login.html),因为下一个"Route 对象没有 url 或其他东西.也许有更好的方法?

The one thing that seems odd is that I had to test the partial name (login.html) because the "next" Route object did not have a url or something else. Maybe there's a better way?

这篇关于根据条件重定向到某个路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 22:50