我有一个 Angular 站点,我在其中插入了一些代码,以使浏览器后退按钮的行为方式与后退 UI 按钮相同。但是,当我在浏览器上按回时,在默认行为执行之前,最后访问的页面会闪烁一秒钟。
这是一个视频来说明我的意思 - 最后我展示了单击 UI 按钮所做的事情,这是我想要模仿的:
Browser Back Button Demo
这是我在 Angular 中使用的代码:
@HostListener('window:popstate', ['$event'])
onBrowserBackBtnClose(event: Event) {
// Stop default behavior of the back button
event.stopPropagation();
event.preventDefault();
// If we can go back...
if (this.canGoBack) {
// Load the previous question
this.questionService.previousQuestion().subscribe(res => {
// Activate the question route in place of the previous page
this.router.navigate(['question'], {replaceUrl: true});
});
}
}
我的理解是 event.stopPropagation();
和 event.preventDefault();
停止这种闪烁的行为?或者还有什么我不理解或遗漏的东西?
最佳答案
如果我是你,我宁愿在这里使用原生 Angular 方法。在这种特殊情况下,您可以实现 CanDeactivate或 CanActivate路线守卫。
在这两个接口(interface)中,方法都使用异步返回,例如:
Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree
关于angular - 浏览器后退按钮默认行为在停止传播时仍在执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63832388/