AngularJS仅在浏览器的后退按钮上重定向路由

AngularJS redirect a route only on browser's back button

本文关键字:按钮 重定向 路由 浏览器 AngularJS      更新时间:2023-09-26

在我的AngularJS应用程序中,当我没有记录用户时,我将route重定向到特定页面。为此,我在$rootScope上使用了一个变量。

现在我想在登录用户时阻止浏览器的后退按钮。 我想将其重定向到特定页面(registration视图)。问题是我不知道是否有后退按钮事件

我的代码是:

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

所以$locationChangeStart我会写一个伪代码,比如:

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

可能吗?

一个

天真的解决方案是编写一个函数来检查nextcurrent的顺序是否错误,检测用户是否要返回

还有其他解决方案吗?我以错误的方式处理问题?

我找到了一个解决方案,这比我想象的要容易。我在$rootScope实际位置的对象上注册,并在每个位置更改时与新位置进行检查。通过这种方式,我可以检测用户是否正在返回历史记录。

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