3

在我的 Angular 2 应用程序中,我使用此处描述的内容提供了 window 对象:Angular2 - How to injection window into an angular2 service

然而,用于 AOT 的 ngc 编译器会返回几个错误。首先,我必须更改提供依赖项的方式(注意“窗口”):

@NgModule({        
  providers: [
    { provide: 'Window',  useValue: window }
  ],
  ...
})
export class AppModule {}

在我的组件中(注意类型'any'):

@Component({ ... })
export default class MyComponent {
    constructor (
        @Inject('Window') private window: any
    ) {}
...

但是,我的模块 ngfactory 中的 ngc 编译器仍然抛出以下错误:

类型上不存在属性“窗口”

再次使用 tsc 编译器一切正常。

4

2 回答 2

2

最后,我完全按照这里的描述解决了我的问题:http: //juristr.com/blog/2016/09/ng2-get-window-ref/

于 2016-11-18T11:51:29.513 回答
1

以下简单的解决方案对我有用:

在“ @NgModule ”下的“ providers ”部分:

{provide: 'window', useFactory: getWindow }

确保导出“getWindow”方法:

export function getWindow() { return window; }

来源 - https://github.com/angular/angular/issues/14050

于 2017-08-20T12:41:40.927 回答