重定向到某条路根据病情 [英] Redirecting to a certain route based on condition

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

问题描述

我正在写一个小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://本地主机/#/主我最终绕过登录屏幕。我想写的东西,如每当路由变化,如果$ rootScope.loggedUser为null,则重定向到/登录

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.

推荐答案

通过一些文档和源$ C ​​$ C一些跳水之后,我觉得我得到它的工作。或许,这将是为别人有用吗?

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" ) {
          // already going to #login, no redirect needed
        } else {
          // not going to #login, we should redirect now
          $location.path( "/login" );
        }
      }         
    });
 })

有一件事似乎奇怪的是,我不得不测试部分名称(的login.html ),因为下一个Route对象没有一个网址或某事其他。也许有更好的方法?

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?

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆