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?
You can get window from injected document.
This is the shortest/cleanest answer that I've found working with Angular 4 AOT
Source: https://github.com/angular/angular/issues/12631#issuecomment-274260009
It's also a good idea to mark the
DOCUMENT
as optional. Per the Angular docs:Here's an example of using the
DOCUMENT
to see whether the browser has SVG support:@maxisam thanks for ngx-window-token. I was doing something similar but switched to yours. This is my service for listening to window resize events and notifying subscribers.
Short and sweet and works like a charm.
This is working for me currently (2018-03, angular 5.2 with AoT, tested in angular-cli and a custom webpack build):
First, create an injectable service that provides a reference to window:
Now, register that service with your root AppModule so it can be injected everywhere:
and then later on where you need to inject
window
:You may also wish to add
nativeDocument
and other globals to this service in a similar way if you use these in your application.edit: Updated with Truchainz suggestion. edit2: Updated for angular 2.1.2 edit3: Added AoT notes edit4: Adding
any
type workaround note edit5: Updated solution to use a WindowRefService which fixes an error I was getting when using previous solution with a different build edit6: adding example custom Window typingBefore the @Component declaration, you can do that too,
The compiler will actually let you then access the global window variable now since you declare it as an assumed global variable with type any.
I wouldn't suggest to access window everywhere in your application though, You should create services that access/modify the needed window attributes (and inject those services in your components) to scope what you can do with the window without letting them to modify the whole window object.