如何在Angular 2中禁用浏览器后退按钮 [英] How to disable Browser back button in Angular 2
本文介绍了如何在Angular 2中禁用浏览器后退按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Angular 2开发一个网站。
有没有办法使用Angular 2禁用或触发浏览器后退按钮?
I'm developing a web site using Angular 2. Is there any way to disable or trigger Browser back button using Angular 2?
谢谢
推荐答案
不确定这是否已经排序,但是尽管如此,仍然可以发布答案,供将来参考。
要解决此问题,您基本上需要在app-component中添加一个监听器并设置 canDeactivate 保护你的角度路由器。
Not sure if this is already sorted, but posting the answer nonetheless, for future references. To tackle this, you basically need to add a listener in your app-component and setup a canDeactivate guard on your angular-router.
// in app.component.ts
import { LocationStrategy } from '@angular/common';
@Component({
selector: 'app-root'
})
export class AppComponent {
constructor(
private location: LocationStrategy
) {
// check if back or forward button is pressed.
this.location.onPopState(() => {
// set isBackButtonClicked to true.
this.someNavigationService.setBackClicked(true);
return false;
});
}
}
// in navigation guard
@Injectable()
export class NavigationGuard implements CanDeactivate<any> {
constructor(private someNavigationService: SomeNavigationService) {}
canDeactivate(component: any) {
// will prevent user from going back
if (this.someNavigationService.getBackClicked()) {
this.someNavigationService.setBackClicked(false);
// push current state again to prevent further attempts.
history.pushState(null, null, location.href);
return false;
}
return true;
}
}
这篇关于如何在Angular 2中禁用浏览器后退按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文