升级到 Angular 16 中断 Sharepoint 广告: this._history.replaceState 不是函数

Ami*_*mir 6 office-addins angular-ui-router office-js angular angular16

我正在升级在 Share Point 办公室内运行的 Angular 应用程序。目前 Angular 应用程序使用的是版本 14,在我升级到 Angular 15 后,它工作正常。但是当我升级到 16 后,我就收到以下错误。

TypeError: this._history.replaceState is not a function
Run Code Online (Sandbox Code Playgroud)

打电话时会发生这种情况

 this.router.navigate(['/path_to_component']);
Run Code Online (Sandbox Code Playgroud)

我在这个 SO 帖子上找到了修复。Office.js 使浏览器历史记录功能无效,破坏历史记录使用情况

<script type="text/javascript">
    // Office js deletes window.history.pushState and window.history.replaceState. Cache them and restore them
    window._historyCache = {
        replaceState: window.history.replaceState,
        pushState: window.history.pushState
    };
</script>

<script type="text/javascript" src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script>

<script type="text/javascript">
    // Office js deletes window.history.pushState and window.history.replaceState. Restore them
    window.history.replaceState = window._historyCache.replaceState;
    window.history.pushState = window._historyCache.pushState;
</script>
Run Code Online (Sandbox Code Playgroud)

我不确定升级到 Angular 16 后会发生什么问题,尽管它与 office.js 有关

我正在使用相同版本的office.js。

我已经使用了哈希位置策略。任何人都可以帮助我理解这一点。

Alb*_*chi 4

查看Angular 14/15的源代码,我们可以看到BrowserPlatformLocation包含这个方法:

override replaceState(state: any, title: string, url: string): void {
    if (supportsState()) {
      this._history.replaceState(state, title, url);
    } else {
      this.location.hash = url;
    }
  }
Run Code Online (Sandbox Code Playgroud)

资料来源:

  1. https://github.com/angular/angular/blob/14.0.x/packages/common/src/location/platform_location.ts#L180C3-L186C4(角度14)
  2. https://github.com/angular/angular/blob/15.0.x/packages/common/src/location/platform_location.ts#L180C3-L186C4(角度15)

您应该注意的是supportsState()

export function supportsState(): boolean {
  return !!window.history.pushState;
}
Run Code Online (Sandbox Code Playgroud)

pushState在 Angular 14/15 中,如果不可用,则有一个后备情况,因此您的代码可以this._history.replaceState()正常运行。

从 Angular 16 开始,该检查已被删除:

override replaceState(state: any, title: string, url: string): void {
    this._history.replaceState(state, title, url);
}
Run Code Online (Sandbox Code Playgroud)

来源:https ://github.com/angular/angular/blob/16.0.x/packages/common/src/location/platform_location.ts#L165

因此,因为office.js删除了pushState并且replaceState没有后备情况,所以您的代码会中断(直到您使用已经找到的修复程序)。