Using Injection Tokens
Use injection tokens to inject static values into a service.
For instance, if you need to use window.history
, then instead of using the global object directly, which would tightly couple your code to the DOM api, declare an injection token and request this dependency in the constructor.
Then, in your module, provide this dependency from the ambient API.
The history can now be mocked in unit tests. Note that this is a truly isolated test as there was no need for nasty tricks like patching the global browser API.
note
Always declare the injection token on the side of the consumer, not on the side of the provider. If multiple consumers need the same value injected, then create a file providers.ts
where you place all injection token declarations. This prevents dependency cycles.