无法使用$ routeChangeStart阻止访问特定路由

时间:2014-07-09 10:33:44

标签: javascript angularjs angularjs-scope angularjs-routing

在角度js中我有一个路由功能,应该管理对管理员和非管理员用户的路由访问,所以我习惯$routeChangeStart根据我的逻辑实现,如果用户登录他不能去那rout '/'(登录页面)。但这不起作用。如果网址匹配http://localhost:3000/#/

,它仍然可以登录
app.run(['$rootScope', 'authService', '$location', function($rootScope, authService, $location){
    $rootScope.$on('$routeChangeStart', function(evt, next, curr){

        if(authService.AccessPrivilegesAuth()){
            if(!authService.AccessPrivilegesAdmin(next.access_level)){
                $location.path('categories');
            }

        }else if(authService.AccessPrivilegesAuth()== false){
            $location.path('/');
        }
    })
}]);

她是登录控制器。

app.controller('LoginController', ['$scope', '$location', 'authService','$cookieStore', function($scope, $location, authService, $cookieStore){
     $scope.loginData = {
         EmailAddress : "",
         password : ""
     };

     $scope.error; $scope.error_exist = false; 
     $scope.login = function(){
         authService.Login($scope.loginData).success(function(response){
             $cookieStore.put('AuthorizationHeader', response.Token);
             authService.isAuth = true;
             authService.IsAdmin = response.IsAdmin;
             var authData = $cookieStore.get('AuthorizationHeader');
             console.log(authData);
             $location.path('categories');
         }).error(function(Error){
             $scope.error_exist = true;
             switch(Error.ExceptionMessage){
                case "201" :
                     $scope.error = "The emailAddress/password pair don't match an existing member"; break;
                case "210" :
                     $scope.error = "Value cannot be null missing Email Address and/or password."; break;
                case "202" :
                     $scope.error = "The email address you are using isn't confirmed. Please see your inbox for further instructions."; break;
                default : 
                     $scope.error = "Error with the server";
             }
         });

     };
 }]);

1 个答案:

答案 0 :(得分:0)

$routeChangeStartpreventDefault()但是我记得它不起作用。不过前段时间我设法使用$locationChangeStart

$locationChangeStart$routeChangeStart之前触发,如果被阻止,则$routeChangeStart根本不会触发。

请注意,我尚未测试此代码:

$rootScope.$on("$locationChangeStart", function(event) {
    if(notAllowed){
        event.preventDefault();
    };
});