Dependency Injection in Angular

Posted By : Prachi Ahuja | 28-Aug-2019

Introduction
Dependency Injection is a feature in angular which helps to build more scalable applications. It is a pattern that works for components to hold the dependencies and angular has its own Dependency Injection framework. This framework helps in creating more efficient angular applications and services or objects are the dependencies in angular.

 

What is Dependency?
When the first module needs the second module to run in an application then the second module is a dependency of the first module. And in a Realistic way, while creating an application we cannot move away from creating dependencies among the modules.

 

 

DI in angular has three things-
 - Injector which helps to create instances of dependencies
 - Provider which tells how to create an instance
 - Dependency is a type for which object should be created

 

Creation of Injectable service
Dependency Injection framework helps the angular application to supply data from service to different components and if we try to combine both components and service then we should define the service first.
We usually inject service using decorator @Injectable and injector is only responsible for the creation of instances of service and then injecting into classes. Angular cannot inject the service anywhere until we configure the injector with the provider of service.

 

Configuration of Injectors - 
 - @Injectable decorator  for service
 - @ngModule decorator for ngModule
 - @component decorator for component.

 

Injector hierarchy and Dependency Injection Token
Angular usually has a hierarchial system for injection and it means that nested injectors can also create their own service instances and then it also creates child injectors. 
A DI token is a provider with which we configure an injector and this injector maintains a particular map that gets referred which asked for the dependency.

 

Conclusion
Dependency Injection is a great feature of angular when we are creating an application with several modules and every single module is dependent on other modules in our application.

 

 

About Author

Author Image
Prachi Ahuja

Prachi is a UI Developer having knowledge of HTML5, CSS3, Javascript, Jquery. She is dedicated towards her work.Her hobbies are drawings/paintings and writing articles.

Request for Proposal

Name is required

Comment is required

Sending message..