TLDR Summary
UseWindowRef
to safely access thewindow
object and/or mock it with a simple to use class and syntax.
The window
object is necessary many times when working with the web, and normally we would summon it directly in our code. However, window
doesn't always exist when working with angular.
Angular serves for many purposes other than web development:
Basically, this means that our application might be run in different environments, others than the normal browser, hence will not have the window
object.
The WindowRef
service acts as an injectable angular wrapper for the javascript window
object.
WindowRef
will automatically detect if it is running on a browser platform and will return an empty object otherwise.
This allows DI and unit testing and prevents "window
is undefined" on non-browser platforms.
The default implementation for WindowRef
depends on the WINDOW
token which provides the actual native object.
This eventually gives you the ability to use the WindowRef
service in your apps and, when needed, mock or provide a different implementation for the service, the WINDOW
token, or both.
Import CoreModule
into your app:
Inject WindowRef
in your components and use .nativeWindow
to access the window
object:
Mocking and replacing implementation