Skip to main content

Dependency injection

  • Dependency injection

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:

https://www.angulartraining.com/daily-newsletter/wp-content/uploads/2023/03/image-22-1024x207.png

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:

https://www.angulartraining.com/daily-newsletter/wp-content/uploads/2023/03/image-23.png

The order of the dependencies in deps has to match the order of the parameters in the factory function passed to useFactory.