Search code examples
javascriptangularjshttp-redirectbackangularjs-routing

AngularJS redirect a route only on browser's back button


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?


Solution

  • 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');
                }
            }); 
        });
    });