Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Inject Window into Angular 2.1.0

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.

like image 805
tt9 Avatar asked Oct 24 '16 15:10

tt9


People also ask

How do you inject a Window into a service?

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.

What is injectable () in Angular?

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.

When we use @inject in Angular?

@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.

Can we inject interface in Angular?

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.


1 Answers

Try with:

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

export class HomeModule {}

in your component:

constructor(@Inject("windowObject") window: Window})
like image 138
Vlado Tesanovic Avatar answered Sep 28 '22 09:09

Vlado Tesanovic