Yesterday, we saw how to use our component (and module) hierarchy to configure dependency injection with Angular.
Today, let’s look at how we can make dependency injection conditional. For instance, say we have a LoginService
for production that requires features unavailable at dev time or that we do not want to use during the development phase.
What we can do then is configure our providers to make a decision based on the current environment:
Using the ternary operator [if true] ? [then this] : [else that]
, we can decide when to use a service over an alternative version.
If you need to make that dependency injection decision depending on other factors, such as data from other services, or if you have several different possible services to inject, you can use a factory function that relies on other services (deps
) that are injected in the factory function as follows:
The order of the dependencies in deps
has to match the order of the parameters in the factory function passed to useFactory
.