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

Atr*_*opo 0 javascript redirect back angularjs angularjs-routing

在我的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);
               });
           });
Run Code Online (Sandbox Code Playgroud)

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

if (event == backButton){
     $location.path('/register');
}
Run Code Online (Sandbox Code Playgroud)

可能吗?

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

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

Atr*_*opo 6

我找到了一个比我想象的更容易的解决方案.我在$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');
            }
        }); 
    });
});
Run Code Online (Sandbox Code Playgroud)