Angular 10:当使用浏览器的后退按钮从外部 URL 导航回来时,ngOnInit 不会在 Firefox 中已部署的应用程序版本中触发

Angular 10: ngOnInit not firing in the deployed app version in Firefox when navigating back from the external URL with browser's back button

我发现已部署的 Angular 应用程序的生命周期在 Firefox 中看起来有所不同。

应用程序组件有一个非常简单的代码:

export class AppComponent implements OnInit {
  public ngOnInit(): void {
    console.log('OnInit');
  }
}

它的html也很简单:

<a href="https://angular.io">Bring me to external URL</a>

我预计会出现以下情况。用户打开应用程序,在控制台中看到 'OnInit',通过 link 导航,单击后退按钮并在控制台中看到新的 'OnInit' 消息(如果日志被保留)。

如果我在任何浏览器中使用 ng serve 在本地 运行 应用程序,它就可以工作。

但如果我使用 ng build --prod 构建应用程序、部署它(例如使用 a command-line http server)并在 Firefox 中打开它,它看起来会有所不同。当我加载应用程序时,我仍然看到 'OnInit' 出现在控制台中。但是当我单击 link 并返回时没有任何反应。未到达 OnInit 内部的代码。看起来组件或整个页面没有重新加载,FF 呈现之前的状态。

它会导致一些讨厌的问题。例如,当用户从第三方 OAuth 登录页面返回时,他们看到的是前一屏幕的错误状态。

我还检查了应用程序内部的导航。对于内部 URL,它在任何地方都可以完美运行。

您能向我解释一下为什么会发生这种情况以及如何在 Firefox 中获取 OnInit 吗?

我找到了相似的 thread on GitHub。但是 Angular 团队认为这不是框架的问题。

问题是由 Angular 而不是 运行 生命周期挂钩引起的,当您从外部 URL 到您的应用时 'return'。

@HostListener("document:visibilitychange", ["$event"])
handleVisibilityChange(event: any): void {

    // Handle stuff

    }
}

代码来自