AngularJS redirect a route only on browser's b

2019-01-23 22:31发布

问题:

In my AngularJS application I'm redirecting the route to a specific page when the user isn't logged. To do that I'm using a variable on $rootScope.

Now I would like to prevent the browser's back button when the user is logged. I would like to redirect it to a specific page (the registration view). The problem is I don't know if there's a back button event.

My code is:

 angular.module('myApp',[...]
//Route configurations
}])
.run(function($rootScope, $location){
               $rootScope.$on('$routeChangeStart', function(event, next, current){
                   if(!$rootScope.loggedUser) { 
                       $location.path('/register');
                   }
               });
               $rootScope.$on('$locationChangeStart', function(event, next, current){
                   console.log("Current: " + current);
                   console.log("Next: " + next);
               });
           });

So on $locationChangeStart I would write a pseudocode like:

if (event == backButton){
     $location.path('/register');
}

Is it possible?

A naive solution would be writing a function that checks if next and current are in the wrong order, detecting if the user is going back.

There are other solutions? I'm approaching the problem in a wrong way?

回答1:

I found a solution, which is easier than I thought. I register on a object in $rootScope the actual location and on every location change I check with the new one. In this way I can detect if the user is going back in the history.

angular.module('myApp',[...], {
    //Route configurations
}])
.run(function($rootScope, $location) {
    $rootScope.$on('$routeChangeStart', function(event, next, current) {
        if(!$rootScope.loggedUser) { 
            $location.path('/register');
        }
    });

    $rootScope.$on('$locationChangeSuccess', function() {
        $rootScope.actualLocation = $location.path();
    });

    $rootScope.$watch(function() { return $location.path() },
        function(newLocation, oldLocation) {
            if($rootScope.actualLocation == newLocation) {
                $location.path('/register');
            }
        }); 
    });
});