Angular Dependency Injection

Posted By : Damandeep Singh | 27-Jun-2018

Let's take an example before writing the definition:

Assume we have three classes as Class A, Class B, Class C. Class A implements sum functionality. Now Class B and Class C also require same sum functionality so instead of writing the code these two classes want to inherit it from class A and here Class A is the service Class.

 

Now one way is to create an instance of class B and Class C and then we can easily use it. this method we have applied in C++ and other languages.

 

But if we consider the memory and time as the main perspective then this code is a failure because if we have 'n' number of classes using the same feature then we have to create 'n' number  of instances for such a case so,

 

'n' memory spaces will be created because every time we create a new object, new memory gets allocated and it will consume a lot of time too. Also, there will be no sharing between these classes.

 

And one More Problem like if we add a new argument to the function then at the time of instance creation we have to add that argument in the instance call else the code fails so it's very difficult to maintain the code.

 

Angular Provides Dependency Injection for solving these problems of time, memory, sharing, and maintenance.

 

We create a class A (service class ) and then we mention that service class in providers either at module level or Component Level. Because with the help of provider only the compiler gets to know about the services we are going to use.

 

Then in the constructor, we declare a private variable of service class type which creates an instance for the service class only once the service gets started. Also if we make any changes in the service class then the instance is overridden instead of creating again.

 

So basically,

  • Dependency injection is a coding pattern in which a class receives its dependencies from any other source rather than creating it themselves.
  • With this we do not need to create an instance of the service, instance gets created by the injector automatically.
  • Also, this helps in creating singleton service that is one service class gets called by 'n' number of classes by creating a single instance for the service class.

About Author

Author Image
Damandeep Singh

Damandeep Singh is a Front-end Developer having Good knowledge of HTML, CSS3/CSS, Bootstrap, Angular, Ionic. He likes to listen to Music in Free time.

Request for Proposal

Name is required

Comment is required

Sending message..