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?
Getting window object via DI(Dependency Injection) is not a good idea when global variables are accessible throughout the application.
But if you don't want to use window object then you can also use
self
keyword which also points to window object.To get it to work on Angular 2.1.1 I had to
@Inject
window using a stringand then mock it like this
and in the ordinary
@NgModule
I provide it like thisI know the question is how to inject the window object into a component but you're doing this just to get to localStorage it seems. If you realy just want localStorage, why not use a service that exposes just that, like h5webstorage. Then you component will describe its real dependencies which makes your code more readable.
As of today (April 2016), the code in the previous solution doesn't work, I think it is possible to inject window directly into App.ts and then gather the values you need into a service for global access in the App, but if you prefer to create and inject your own service, a way simpler solution is this.
https://gist.github.com/WilldelaVega777/9afcbd6cc661f4107c2b74dd6090cebf
Here's another solution I came up recently after I got tired of getting
defaultView
fromDOCUMENT
built-in token and checking it for null:You can use NgZone on Angular 4: