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

标签 angular typescript

我有一个 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 方法。在这种特殊情况下,您可以实现 CanDeactivateCanActivate路线守卫。
在这两个接口(interface)中,方法都使用异步返回,例如:

Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree

关于angular - 浏览器后退按钮默认行为在停止传播时仍在执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63832388/

相关文章:

node.js - 使用 sequelize 和 typescript 自动迁移

node.js - formData 通过 http.post 在 Angular + NodeJS 中

Angular HttpClient 简单 GET 发送预检选项。我如何强制我的 GET 保持简单请求?

javascript - 为什么我的应用程序组件会呈现一个应用程序组件?

TypeScript 声明模块

angular - 使用导出 const 变量的 Webpack treeshaking

angularjs - Angular 2 : PrimeNG - XHR error (404 Not Found)

enums - Typescript 枚举,用于实现和接口(interface)

angular - Ionic 3,用于管道的共享模块,用于延迟加载的页面

angular2 和 window.URL.createObjectURL