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 array.
Since upgrading to the latest stable release of angular 2 (2.1.0) this now throws a console error
compiler.umd.js:14268Uncaught Error: Can't resolve all parameters for LoginComponent: (AuthService, UserMessagesService, ?).
The ? in the parameter list is where I am trying to inject the Window object.
To inject window into a service with Angular, we can inject document into our service. Then we get window from document . to inject document with @Inject(DOCUMENT) private document: Document in the constructor signature. Then we get window from this.
The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency. Likewise, the @Injectable() decorator indicates that a component, class, pipe, or NgModule has a dependency on a service. The injector is the main mechanism.
@Injectable() lets Angular know that a class can be used with the dependency injector. @Injectable() is not strictly required if the class has other Angular decorators on it or does not have any dependencies. What is important is that any class that is going to be injected with Angular is decorated.
No, interfaces are not supported for DI. With TypeScript interfaces are not available at runtime anymore, only statically and therefore can't be used as DI tokens.
Try with:
@NgModule({
declarations: [...],
imports: [...],
providers: [
{ provide: "windowObject", useValue: window}
]
})
export class HomeModule {}
in your component:
constructor(@Inject("windowObject") window: Window})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With