我正在升级在 Share Point 办公室内运行的 Angular 应用程序。目前 Angular 应用程序使用的是版本 14,在我升级到 Angular 15 后,它工作正常。但一旦我升级到 16,我就会收到以下错误。
TypeError: this._history.replaceState is not a function
打电话时会发生这种情况
this.router.navigate(['/path_to_component']);
我在这篇文章中找到了修复。 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>
我不确定升级到 Angular 16 后它是如何被破坏的,尽管它与 Office.js 相关
我使用的是相同版本的office.js。
我已经使用了哈希位置策略。任何人都可以帮助我理解这一点吗?
查看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;
}
}
来源:
你应该注意的是
supportsState()
:
export function supportsState(): boolean {
return !!window.history.pushState;
}
在 Angular 14/15 中,如果
pushState
不可用,会有后备情况,因此您的代码可以正常工作。
从 Angular 16 开始,该检查已被删除:
override replaceState(state: any, title: string, url: string): void {
this._history.replaceState(state, title, url);
}
因此,因为
office.js
删除了 pushState
和 replaceState
并且没有后备情况,所以您的代码会损坏(您使用已经找到的修复程序的单元)。