我有两个使用这些版本的 Angular 项目:
在版本 9 中,我使用它来提供和注入(inject)
window
对象:@NgModule({
providers: [
{
provide: Window,
useValue: window
},
]
})
export class TestComponent implements OnInit {
constructor(@Inject(Window) private window: Window)
}
哪个工作正常。
将这种方法应用于版本 8 会在编译期间引发警告和错误:
Warning: Can't resolve all parameters for TestComponent …
我通过使用单引号解决了它,如下所示:
@NgModule({
providers: [
{
provide: 'Window',
useValue: window
},
]
})
export class TestComponent implements OnInit {
constructor(@Inject('Window') private window: Window)
}
两个版本有什么区别?
导致这件事的 Angular 8 和 9 有什么区别?
最佳答案
为了让您的应用程序与服务器端渲染一起工作,我建议您不仅通过 token 使用窗口,而且还以 SSR 友好的方式创建此 token ,而不引用 window
一点也不。 Angular 内置了 DOCUMENT
用于访问 document
的 token .这是我为我的项目想出的 window
通过 token :
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;
},
},
);
编辑:由于这是人们经常需要的东西,我们使用这种技术创建了一个带有全局对象注入(inject) token 的小型开源库,因此您可以使用它:https://github.com/ng-web-apis/common
它有一个姊妹库,用于模拟在 Angular Universal 中与 SSR 一起使用:
https://github.com/ng-web-apis/universal
总体而言,请查看我们的 Angular 原生 API 中心:
https://ng-web-apis.github.io/
关于javascript - 在 Angular 8 和 9 中提供和注入(inject) 'Window' 与 Window 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58873919/