为了让您的应用程序能够使用服务器端渲染,我建议您不仅使用窗口令牌,而且还以 SSR 友好的方式创建此令牌,而无需引用window
根本不。 Angular 内置了DOCUMENT
用于访问的令牌document
。这是我为我的项目使用的想法window
通过代币:
import {DOCUMENT} from '@angular/common';
import {inject, InjectionToken} from '@angular/core';
export const WINDOW = new InjectionToken<Window>(
'An abstraction over global window object',
{
factory: () => {
const {defaultView} = inject(DOCUMENT);
if (!defaultView) {
throw new Error('Window is not available');
}
return defaultView;
},
},
);
Edit:由于这是人们经常需要的东西,我们使用这种技术创建了一个小型开源库,其中包含全局对象的注入令牌,因此您可以使用它:
https://github.com/ng-web-apis/common https://github.com/ng-web-apis/common
它有一个姊妹库,用于在 Angular Universal 中与 SSR 一起使用模拟:
https://github.com/ng-web-apis/universal https://github.com/ng-web-apis/universal
总的来说,请查看我们的 Angular 原生 API 中心:
https://ng-web-apis.github.io/ https://ng-web-apis.github.io/