How do I check for login or other status before launching a route in Angular with routeProvider?

后端 未结 3 2069
耶瑟儿~
耶瑟儿~ 2021-02-14 11:39

Let\'s say I have 4 routes - 2 require the user to be logged in, 2 do not. My app init looks like:

        $routeProvider.when(\'/open1\',{templateUrl:\'/open1.h         


        
3条回答
  •  眼角桃花
    2021-02-14 12:05

    This blog post deals with user authentication in AngularJS using directives.

    The $route service emits $routeChangeStart before a route change.

    If you don't use directives, you can catch that event by calling app.run (you can place it after the code where you define the routes [app.config]). For example:

    For full disclosure I use ui.router and this is an adapted code from $stateChangeStart I use in my app

    var app = angular.module('app');
    
    app.config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/open1',{templateUrl:'/open1.html',controller:'Open1'});
        $routeProvider.when('/open2',{templateUrl:'/open2.html',controller:'Open2'});
        $routeProvider.when('/secure1',{templateUrl:'/secure1.html',controller:'Secure1'});
        $routeProvider.when('/secure2',{templateUrl:'/secure2.html',controller:'Secure2'});
    }]);
    
    app.run(['$rootScope', '$location', 'Auth', function($rootScope, $location, Auth) {
        $rootScope.$on('$routeChangeStart', function(event, currRoute, prevRoute){
            var logged = Auth.isLogin();
    
            //check if the user is going to the login page
            // i use ui.route so not exactly sure about this one but you get the picture
            var appTo = currRoute.path.indexOf('/secure') !== -1;
    
            if(appTo && !logged) {
                event.preventDefault();
                $location.path('/login');
            }
        });
    }]);
    

提交回复
热议问题