AngularJS重定向只对浏览器的后退按钮路由 [英] AngularJS redirect a route only on browser's back button
问题描述
在我的AngularJS应用我重定向路线
到一个特定的网页时,不登录的用户。要做到这一点我使用 $ rootScope
的变量。
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
.
现在我想,当用户登录到prevent浏览器的后退按钮。我想它重定向到一个特定的页面(即注册
视图)。问题是我不知道是否有一个的后退按钮事件的
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.
我的code是:
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
我会写一个伪code,如:
So on $locationChangeStart
I would write a pseudocode like:
if (event == backButton){
$location.path('/register');
}
这可能吗?
一个天真的解决办法是写一个检查功能,如果接下来
和电流
是在错误的顺序,检测如果用户的回去的
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?
推荐答案
我找到了解决办法,这比我想象的容易。我在注册 $ rootScope
一个对象的实际位置上,并在每个位置更改我用新的检查。通过这种方式,如果用户在历史可以追溯到我能察觉。
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');
}
});
});
});
这篇关于AngularJS重定向只对浏览器的后退按钮路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!