AngularJS:根据用户是否获得授权,使用angularjs保护路由?

Mar*_*tin 11 angularjs angularjs-directive angularjs-scope

我刚刚开始使用AngularJS我正在开发的应用程序,一切进展顺利但我需要一种保护路由的方法,以便在没有登录时不允许用户进入该路由.我理解的重要性在服务方面也要保护,我会照顾这个.

我找到了许多保护客户端的方法,似乎使用了以下内容

$scope.$watch(
    function() {
        return $location.path();
    },
    function(newValue, oldValue) {
        if ($scope.loggedIn == false && newValue != '/login') {
            $location.path('/login');
        }
    }
);
Run Code Online (Sandbox Code Playgroud)

我在哪里需要把这个,在.runapp.js

我找到的另一种方法是使用指令并使用on-routechagestart

信息在这里 http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app

我真的对任何人的推荐方式的帮助和反馈感兴趣.

Cla*_*Pan 19

使用做出决议应该可以帮到你:(代码没有经过测试)

angular.module('app' []).config(function($routeProvider){
    $routeProvider
        .when('/needsauthorisation', {
            //config for controller and template
            resolve : {
                //This function is injected with the AuthService where you'll put your authentication logic
                'auth' : function(AuthService){
                    return AuthService.authenticate();
                }
            }
        });
}).run(function($rootScope, $location){
    //If the route change failed due to authentication error, redirect them out
    $rootScope.$on('$routeChangeError', function(event, current, previous, rejection){
        if(rejection === 'Not Authenticated'){
            $location.path('/');
        }
    })
}).factory('AuthService', function($q){
    return {
        authenticate : function(){
            //Authentication logic here
            if(isAuthenticated){
                //If authenticated, return anything you want, probably a user object
                return true;
            } else {
                //Else send a rejection
                return $q.reject('Not Authenticated');
            }
        }
    }
});
Run Code Online (Sandbox Code Playgroud)