javascript – 如何在Angular 2中禁用浏览器后退按钮
作者:互联网
我正在使用Angular 2开发一个网站.
有没有办法使用Angular 2禁用或触发浏览器后退按钮?
谢谢
解决方法:
不确定这是否已经排序,但仍然发布答案,以供将来参考.
要解决这个问题,您基本上需要在app-component中添加一个监听器,并在angular-router上设置一个canDeactivate防护.
// 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;
}
}
标签:javascript,angular,back-button 来源: https://codeday.me/bug/20190929/1830481.html