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?
Angular 4 introduce InjectToken, and they also create a token for document called DOCUMENT. I think this is the official solution and it works in AoT.
I use the same logic to create a small library called ngx-window-token to prevent doing this over and over.
I have used it in other project and build in AoT without issues.
Here is how I used it in other package
Here is the plunker
In your module
imports: [ BrowserModule, WindowTokenModule ]
In your componentconstructor(@Inject(WINDOW) _window) { }
There is an opportunity for direct access to the object of window through the document
You can just inject it after you've set the provider: