浏览器后退按钮默认行为仍在停止传播时执行

Web*_*olf 5 typescript angular

我有一个 angular 站点,我在其中插入了一些代码以使浏览器后退按钮的行为与后退 UI 按钮的行为相同。但是,当我按回浏览器时,在执行默认行为之前,最后访问的页面会闪烁一秒钟。

这是一个视频来展示我的意思 - 最后我展示了点击 UI 按钮的作用,这是我想要模拟的: 浏览器后退按钮演示

这是我在 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});
        });
      }
  }
Run Code Online (Sandbox Code Playgroud)

我的理解是,event.stopPropagation();event.preventDefault();停止了这种闪烁的行为?或者还有什么我不理解或遗漏的吗?

Tim*_*thy 1

如果我是你,我宁愿在这里使用原生 Angular 方法。在这种特殊情况下,您可以实施CanDeactivateCanActivate Route Guards。

在这两个接口中,方法都使用异步返回,例如:

可观察<布尔值 | 网址树> | 承诺<布尔值 | 网址树> | 布尔 | 网址树