问题描述
在我的 AngularJS 应用程序中,当用户未登录时,我将 route
重定向到特定页面.为此,我在 $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
.
现在我想在用户登录时阻止浏览器的后退按钮.我想将其重定向到特定页面(registration
视图).问题是我不知道是否有后退按钮事件.
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.
我的代码是:
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
上我会写一个伪代码,如:
So on $locationChangeStart
I would write a pseudocode like:
if (event == backButton){
$location.path('/register');
}
有可能吗?
一个简单的解决方案是编写一个函数来检查 next
和 current
的顺序是否错误,检测用户是否返回.
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 仅在浏览器的后退按钮上重定向路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!