我需要防止用户在我正在构建的应用程序的某些部分中向后导航。到目前为止,我正在使用此方法:
ngOnInit() {
history.pushState(null, null, location.href);
window.onpopstate = function(event) {
history.go(1);
};
}
ngOnDestroy() {
window.onpopstate = function(event) {
history.go();
};
}
除了iOS chrome和safari之外,这工作得很好。我也试过:
history.replaceState(null, document.title, location.pathname);
在 ngOnInit 没有运气。有人可以启发我这些移动设备上的浏览器使用历史记录和/或流行状态的方式与Windows/macOS版本的浏览器有何不同吗?
与其尝试实现不同的特定于浏览器的解决方案,我会考虑 Angular 的CanDeactivate
卫士。
假设您有一个服务(我们称之为 NavigatorService
(,它始终存储以前的路由:
@Injectable()
export class NavigatorService{
private previousRoute:string = null;
private currentRoute:string = null;
/** Listen to and log new route paths */
constructor(private router:Router){
router.events.filter(e => e instanceof NavigationEnd).subscribe(
e => {
this.previousRoute = this.currentRoute;
this.currentRoute = e['url'];
}
)
}
/** Checks whether the next route corresponds to the previous route */
isGoingBack(nextState:RouterStateSnapshot){
return nextState.url === this.previousRoute;
}
}
接下来创建一个 CanDeActivateGuard,该 CanDeActivateGuard 将依赖于此服务来确定是否允许用户导航离开当前视图:
@Injectable()
export class BackwardGuard implements CanDeactivate<any> {
// Inject the service needed
constructor(navigatorService:NavigatorService){}
// Angular 4 provides these arguments to any CanDeactivate guard
// see https://angular.io/api/router/CanDeactivate#interface-overview
canDeactivate(component:any, currentRoute:ActivatedRouteSnapshot,
currentState:RouterStateSnapshot, nextState:RouterStateSnapshot){
// Allow navigation only if the user is not going back
return !this.navigatorService.isGoingBack(nextState);
}
}
最后,在要保护其组件免受向后导航的路由上注册此防护:
appRoutes:Routes = [
{
path: 'some-path',
component: ProtectedComponent,
canDeactivate: [BackwardGuard]
}
];
这个未经测试的代码中可能存在错误,但我认为一旦你解决了它们,它应该可以工作。请记住向组件的模块提供NavigatorService
(例如:AppModule
(,并向匹配的路由模块提供BackwardGuard
(例如:AppRoutingModule
(