Use window as a provider in Angular2

Sometime the project need to access window object in Angular2. Here is the best and easiest way I found.

First, use OpaqueToken to create a token for the provider. It need to be in a separated file, which is other than the one for ngModule.

Otherwise, it will cause circular dependency issue.

create window provider
1
export const WindowSrv = new OpaqueToken("WindowSrv");

then import this token to ngModule.

in ngModule
1
import { WindowSrv } from './app.service';

Add it to providers array

in ngModule
1
2
3
4
5
providers: [ // expose our Services and Providers into Angular's dependency injection
ENV_PROVIDERS,
APP_PROVIDERS,
{ provide: WindowSrv, useValue: window }
]

Then it can be use everywhere like this. Since it is not a class dependency, it needs to use @Inject decorator. Remember to import this token as well.

in component
1
2
3
constructor(
@Inject(WindowSrv) private _Window: Window
) { }

Ref:

  1. DEPENDENCY INJECTION IN ANGULAR 2

  2. Dependency injection tokens

  3. OpaqueToken