Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
668 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...