I'm writing an Angular 2 service in TypeScript that will make use of localstorage
. I want to inject a reference to the browser window
object into my service since I don't want to reference any global variables like Angular 1.x $window
.
How do I do that?
I used OpaqueToken for 'Window' string:
And used just to import
WINDOW_PROVIDERS
in bootstrap in Angular 2.0.0-rc-4.But with the release of Angular 2.0.0-rc.5 I need to create a separate module:
and just defined in the imports property of my main
app.module.ts
In Angular RC4 the following works which is a combination of some of the above answers, in your root app.ts add it the providers:
Then in your service etc inject it into the constructor
It is enough to do
and do
to make AOT happy
With the release of angular 2.0.0-rc.5 NgModule was introduced. The previous solution stopped working for me. This is what I did to fix it:
app.module.ts:
In some component:
You could also use an OpaqueToken instead of the string 'Window'
Edit:
The AppModule is used to bootstrap your application in main.ts like this:
For more information about NgModule read the Angular 2 documentation: https://angular.io/docs/ts/latest/guide/ngmodule.html
Keep it simple, folks!
Actually its very simple to access window object here is my basic component and i tested it its working