0

route在我的 AngularJS 应用程序中,当用户未登录时,我将其重定向到特定页面。为此,我在$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');
}

是否可以?

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

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

4

1 回答 1

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');
            }
        }); 
    });
});
于 2013-10-31T11:37:39.620 回答