Angular 6 Dependency Injection as a Framework

Posted By : Rajan Rawat | 13-Aug-2018

Angular 6 Dependency Injection

Dependency Injection is a mechanism that makes an object that makes depend on the other objects. Injection is a system that supplies the dependencies or objects when we will create an instance of the object.

This post describes you how in angular 6 Dependency Injection will works.

This feature has been always one of the smartest features of angular. It allows you and authorizes you to inject the dependencies in every component throughout the application and you don't need to know how that dependency is created. In the previous version of angular 1.0 it has some problem but in this latest version angular 6, it becomes so easy and useful for us.

Dependency Injection as  Design Pattern

we will discuss the first of dependency injection i.e dependency injection as a pattern. Take a look at the below code for that

class car   
{  
    constructor()   
    {  
        this.fruit = new Fruit();  
            this.mango = Mango.getInstance();  
            this.apple = app.get('apples');  
    }  
}  
        

In the above code we have a class fruit which has a constructor in that then we need to set up each and everything to construct a car object when it is needed. Now in the above code constructor will assigns the dependencies that are needed to all the internal properties. This makes the code hard to understand and maintain and test as well. Just in case if you want to test the class car. How you will replace the 
fruits with

fresh fruits dependency in your code. We have to make code which is reusable but we also have to make the code work in every scenarios and environment with all the dependencies. Which makes the code reusable and testable as well. 

 

Dependency Injection as  Framework

Now we discuss the dependency injection as a framework. Angular 6 has it own dependency injection system that will allow injector to find the dependencies that need to be instantiated. This is will also annotate the services to find the injector

dependency injection is having the three things

Provider -  You can call it as a commander that will tell the injector how to they will create the instance of dependency. The provider will take the token and maps the token to the factory.

injector - This object will expose API to you and create the instance of the dependency.

 

- this is a type of object that will be created  

 

 

 

About Author

Author Image
Rajan Rawat

Rajan is a UI Developer, having good knowledge of HTML, CSS and javascript. His hobbies are internet surfing and watching sports.

Request for Proposal

Name is required

Comment is required

Sending message..