How to Inject Window into Angular 2.1.0

前端 未结 2 1439
终归单人心
终归单人心 2020-12-09 19:56

In the earlier RC releases of Angular 2 I was able to inject the window object by adding

{provide: Window, useValue: window}

To the providers

相关标签:
2条回答
  • 2020-12-09 20:05

    Try with:

    @NgModule({
      declarations: [...],
      imports: [...],
      providers: [
       { provide: "windowObject", useValue: window}
      ]
    })
    

    export class HomeModule {}

    in your component:

    constructor(@Inject("windowObject") window: Window})
    
    0 讨论(0)
  • 2020-12-09 20:18

    In order for it to work with AOT you need to do useFactory instead of useValue:

    export function windowFactory() {
      return window;
    }
    

    module:

    providers: [
       { provide: 'window', useFactory: windowFactory }
    ]
    

    component:

    constructor(@Inject('window') window: Window})
    
    0 讨论(0)
提交回复
热议问题