Ant*_*ony 6 javascript angular
我需要阻止用户在我正在构建的应用程序的某些部分进行向后导航.到目前为止,我正在使用这种方法:
ngOnInit() {
history.pushState(null, null, location.href);
window.onpopstate = function(event) {
history.go(1);
};
}
ngOnDestroy() {
window.onpopstate = function(event) {
history.go();
};
}
Run Code Online (Sandbox Code Playgroud)
除了iOS chrome和safari之外,这项工作非常有效.我也尝试过:
history.replaceState(null, document.title, location.pathname);
Run Code Online (Sandbox Code Playgroud)
在ngOnInit没有运气.有人可以告诉我这些移动设备上的浏览器如何使用历史记录和/或popstate不同于Windows/macOS版本的浏览器?
我不会尝试实现不同的特定于浏览器的解决方案,而是考虑 Angular 的CanDeactivateGuard。
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;
}
}
Run Code Online (Sandbox Code Playgroud)
接下来创建一个 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);
}
}
Run Code Online (Sandbox Code Playgroud)
最后,在您想要保护其组件免受向后导航影响的路由上注册此防护:
appRoutes:Routes = [
{
path: 'some-path',
component: ProtectedComponent,
canDeactivate: [BackwardGuard]
}
];
Run Code Online (Sandbox Code Playgroud)
这个未经测试的代码中可能存在错误,但我认为一旦你解决了它们,它应该可以工作。请记住提供NavigatorService给您的组件的模块(例如:AppModule)并提供BackwardGuard给匹配的路由模块(例如:AppRoutingModule)
| 归档时间: |
|
| 查看次数: |
622 次 |
| 最近记录: |