Angular Dependency Injection — Using “Injector” Service instead of long list of services in Component’s constructor
--
The Angular framework provides Dependency Injection (DI) out of the box. The easiest way to understand DI is to “Delegate creation of instance task to a global authority and just ask for the instance when you want to use it”.
Let’s make it simple, when we create a new service say OrdersService
and provide it in a Root module, the @Injector({ providedIn:'root'})
decorator let Angular compiler know to register this class in a DI registry. It takes care of creating a new service instance internally so that its consumer doesn’t need to write code like let service = new OrdersService()
. When a component needs OrdersService
, it can ask for its instance by putting it in a constructor constructor(private ordersService: OrdersService){}
. The Angular DI will check if it has OrdersService
provided in its registry with all dependencies. If it is a first request for a service instance, then DI will create a new instance and pass it on, otherwise it will just pass on the existing service instance.
Challenges with Service Injection
So far, so good. The challenge would arise when you are working on an enterprise Angular application with tons of services and components. It won’t be unusual to see 10–15 services being injected into the component’s constructor.
For example, below component is injecting six services.
Another challenge would be with inheritance. If you need to derive a child component from ProductDetailsComponent
then you need to provide all these services explicitly as shown below.
The derived component needs to inject these services first and then pass it to its…