根据条件重定向到某条路线 - Redirecting to a certain route based on condition

问题:

I'm writing a small AngularJS app that has a login view and a main view, configured like so: 我正在编写一个小的AngularJS应用,该应用具有登录视图和主视图,其配置如下:

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

My LoginController checks the user/pass combination and sets a property on the $rootScope reflecting this: 我的LoginController检查用户/密码组合,并在$ rootScope上设置一个属性,以反映此情况:

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.";
    }
}

Everything works, but if I access http://localhost/#/main I end up bypassing the login screen. 一切正常,但是如果我访问http://localhost/#/main我最终将绕过登录屏幕。 I wanted to write something like "whenever the route changes, if $rootScope.loggedUser is null then redirect to /login" 我想写一些类似的内容,“每当路由更改时,如果$ rootScope.loggedUser为null,则重定向到/ login”

... ...

... wait. ...等等。 Can I listen to route changes somehow? 我可以听路线变化吗? I'll post this question anyway and keep looking. 无论如何,我都会发布这个问题并继续寻找。


解决方案:

参考一: https://en.stackoom.com/question/mQWN
参考二: https://stackoom.com/question/mQWN
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章