Dependency Injection is the heart of Angular applications. Dependency Injection is a “25 dollar” term used for “10 cents” work. Sometimes, it is a very confusing term for beginner and intermediate developers. In this article, we will learn what Dependency Injection is and how it works.







Dependency Injection is a combination of two terms, those are “Dependency” and “Injections”. Dependency is an object or service that can be used in any another object and Injection is a process of passing the dependency to a dependent object. It creates a new instance of class along with its required dependencies.

In Angular 1, we can inject dependency in different ways and at different place of the application.

At Controller Level

app.controller(‘newController’, function ($scope,$http,mathService)])

At Directive Level

app.directive( 'newDirective' , function ($http, mathService) {}

In Angular 2, we inject dependency via constructor of the class.

Example

import { Injectable,Inject } from '@angular/core' ; import {LoggerService} from './logger.service' ; export class NumListService { list:number[]=[]; constructor(@Inject(LoggerService) private loggerServcie) { } public addNum(num:number){ this .list.push(num); this .loggerServcie.log( "addNum" ); } public getList(){ this .loggerServcie.log( "getList" ); return this .list; } }

In the above code, we have injected the “NumListServcie” dependency in constructor and made the “numList” object of “NumListServcie” type.

Dependency Injection in Angular 2

Dependency Injection in Angular 2 consists of three aspects.

Injector

The injector object is used to create an instance of a dependency. The injector is a mechanism that provides a method using which a dependency is instantiated. To create a dependency, an injector looks for a provider. Let’s take an example.

import { ReflectiveInjector } from '@angular/core' ; var Injector=ReflectiveInjector.resolveAndCreate([MathematicsService,AnotherSrvcie]); var Math=Injector.get(MathematicsService);

In the above code, we implement “ReflectiveInjector” from Angular, that provides some APIs to create an Injector.

You can see several methods of “ReflectiveInjector” that are used to create an Injector in different ways. We used the “resloveAndCreate()” method to create an injector. This method is actually a factory method that creates an injector and takes a list of providers.

You can find more about the “resolveAndCreate” method in definition of this method.

When we need the “MathematicsService”, we tell the Injector to get it for us.

Note - During the development, we don’t need to define the Injector. Angular application manages all of this internally. In the above example, we took an example of how Injector works in Angular.

Provider

A provider is a mechanism using which we register our dependency to be injected. In Angular, we can register our dependency at two levels.

At App Level

Registering the dependency at app level creates the injected dependency singleton.

@NgModule({ declarations: [ AppComponent, CustomDirective, NgNifDirective, Comp1Component, Comp2Component ], imports: [ BrowserModule, FormsModule, HttpModule, CommonModule ], providers:[NumListService,LoggerService], bootstrap: [AppComponent] }) export class AppModule { }

At Component Level

You can also register the dependency at component level. There a new instance of the dependency will create.

import { Component } from '@angular/core' ; import {NumListService} from '../num-list.service' @Component({ selector: 'app-comp1' , templateUrl: './comp1.component.html' , providers:[NumListService], styleUrls: [ './comp1.component.css' ] }) export class Comp1Component { constructor( private numList:NumListService) { } list:number[]=[]; public AddNum(value:number){ this .numList.addNum(value); this .list= this .numList.getList(); } }

Dependency

The dependency that we are injecting in a constructor is an object of the class that we want to use in another class.

import { Component } from '@angular/core' ; import {NumListService} from '../num-list.service' @Component({ selector: 'app-comp1' , templateUrl: './comp1.component.html' , providers:[NumListService], styleUrls: [ './comp1.component.css' ] }) export class Comp1Component { constructor( private numList:NumListService) { } list:number[]=[]; public AddNum(value:number){ this .numList.addNum(value); this .list= this .numList.getList(); } }

What’s a Service in Angular 2

Services are a piece of code that are used to perform a specific task, a service can contain a value or function or combinations of both. Services are injected into application using dependency injection mechanism. Services prevent us from writing the same code at multiple sections of our application. The best solution is to write services are inject in application where we need it. Services provide, store, and interact with data, and a communication channel b/w classes. Service is a mechanism used to share the functionality b/w the components.

Create a service

Now, open your command line interface and write this “ng generate service Mathematics” command and press enter. This command will create a “mathematics” services in your project.

Now, open your “mathematics.service.ts” file you will get the below code. Here, “@Injectable” is metadata that defines this class as injectable instance (servcie). The Injectable decorator makes our service injectable to a component or directives and we can also create instance of this services in any other service.

import { Component } from '@angular/core' ; import {NumListService} from '../num-list.service' @Component({ selector: 'app-comp1' , templateUrl: './comp1.component.html' , providers:[NumListService], styleUrls: [ './comp1.component.css' ] }) export class Comp1Component { constructor( private numList:NumListService) { } list:number[]=[]; public AddNum(value:number){ this .numList.addNum(value); this .list= this .numList.getList(); } }

Now, we add, multiply, subtract, and divide method in this service.

Code

import { Injectable } from '@angular/core' ; @Injectable() export class MathematicsService { constructor() { } public Sum( fValue:number, sValue:number){ return parseInt(fValue.toString())+parseInt(sValue.toString()); } public Sub( fValue:number, sValue:number){ return fValue-sValue; } public Mul( fValue:number, sValue:number){ return fValue*sValue; } public Div( fValue:number, sValue:number){ return fValue/sValue; } }

Add the below code in your component’ template file.

<div [ngStyle]= "{'width':'450px', 'margin-left':'150px','border':'4px solid #7142f4'}" > <h3 [ngStyle]= "{'color':'#42f46e','font-size':'26px'}" > {{name}} </h3> Fvalue:<input type= "text" [(ngModel)]= "fvalue" /> <br/> Lvalue:<input type= "text" [(ngModel)]= "lvalue" /> <br/> <input type= "button" value= "Sum" (click)= "Sum(fvalue,lvalue)" /> <br/> <input type= "button" value= "Sub" (click)= "Sub(fvalue,lvalue)" /> <br/> <input type= "button" value= "Mul" (click)= "Mul(fvalue,lvalue)" /> <br/> <input type= "button" value= "Div" (click)= "Div(fvalue,lvalue)" /> <br/> <span>{{data}}</span> </div>

In this code, we created two textboxes and bound “fValue” and “lValue” models with these. We also created four buttons and on the click event of these buttons, we are calling Sum, Sub, Mul, and Div functions respectively, that are defined in component’s class.

App.component.ts

import { Component,Input,Output,EventEmitter } from '@angular/core' ; import {MathematicsService} from './mathematics.service' ; @Component({ selector: '[app-root]' , templateUrl: './app.component.html' , styleUrls: [ './app.component.css' ] }) export class AppComponent { name:String = 'This is servcie example' ; data:string; MathServcie:MathematicsService= new MathematicsService(); Sum(fValue:number,lvalue:number){ this .data=String( this .MathServcie.Sum(fValue,lvalue)); } Sub(fValue:number,lvalue:number){ this .data=String( this .MathServcie.Sub(fValue,lvalue)); } Mul(fValue:number,lvalue:number){ this .data=String( this .MathServcie.Mul(fValue,lvalue)); } Div(fValue:number,lvalue:number){ this .data=String( this .MathServcie.Div(fValue,lvalue)); }

In component, we imported the “MathematicsService” service and created Sum, Sub, Mul and Div function. In these functions, we are calling the Sum,Sub,Mul and Div functions of the “MathematicsService” service and result retrieved by these function is copied into “data” variable.

Output

Code of component’ template will render the below code in browser.

Now, insert some value into fvalue and Lvalue textbox and click on any button. When we click on any button, a function of component will call and this function internally call another function of “MathematicsService” service and we get the result.

In Angular, we can create single or multiple instance of services depend upon the place where we register the dependency for example if we have multiple components and we register the dependency(service in our case) at component level then two instance of service will create or if we register our dependency at root level in @ngModel then only single instance of the service will be created.

Let’s take an example for better understanding.

Multiple Instance

Now, we will create a “NumListService” service. This Service will add a new number in list and return the list to required object.

NumListServcie

import { Injectable } from '@angular/core' ; @Injectable() export class NumListService { list:number[]=[]; constructor() { } public addNum(num:number){ this .list.push(num); } public getList(){ return this .list; } }

We have created “addNum” method that takes an number and add this number in list. getList() method return this the latest data of the list.

Now, we will create a new component and named as “comp1”. Below is the template and component of Comp1.

Comp1.component.ts

import { Component } from '@angular/core' ; import {NumListService} from '../num-list.service' @Component({ selector: 'app-comp1' , templateUrl: './comp1.component.html' , providers:[NumListService], styleUrls: [ './comp1.component.css' ] }) export class Comp1Component { constructor( private numList:NumListService) { } list:number[]=[]; public AddNum(value:number){ this .numList.addNum(value); this .list= this .numList.getList(); } }

Comp1.component.html

<p> comp1 works! < <input type= "text" [(ngModel)]= "value" /> <input type= "button" value= "Add" (click)=AddNum(value) /> <br/> <br/> <ul> <li *ngFor= "let data of list" >{{data}}</li> </ul>

In template of the component, we have created a textbox and button. On click event of the button, we get the value of “value” model that is bind to textbox and pass as a parameter of “Addnum” method. In “Addnum” method we are calling the “AddNum” method of the “NumListService” and also getting the new updated list from “NumListService”. In “Comp1” component we inject “NumListServcie” dependency at component level.

Now, we will create another component and makes the component and template same as “Comp1” component.

Comp2.component.html

<p> comp2 works! </p> <input type= "text" [(ngModel)]= "value" /> <input type= "button" value= "Add" (click)=AddNum(value) /> <br/> <br/> <ul> <li *ngFor= "let data of list" >{{data}}</li> </ul>

Comp2.component.ts

import { Component } from '@angular/core' ; import {NumListService} from '../num-list.service' @Component({ selector: 'app-comp2' , templateUrl: './comp2.component.html' , providers:[NumListService], styleUrls: [ './comp2.component.css' ] }) export class Comp2Component { constructor( private numList:NumListService) { } list:number[]=[]; public AddNum(value:number){ this .numList.addNum(value); this .list= this .numList.getList(); } }

Now, both components are ready. We will use these components in “app” component that is the parent component of both.

<app-comp1></app-comp1> <br/> <app-comp2></app-comp2>

When you open or refresh the project you will get the below output in your browser screen.

Now, add some values for comp1 and comp2. When you add any values for Comp1 it will not reflect in Comp2 output and also vice versa.The reason is that we register our dependency (service) at component level, it means when we register the service using provider at component level a new instance of the service is always created that will be completely unaware of the instance of the other components.

Single Instance of Service

Instead of component level if we register the service at root level in “App.module” then it will provide a single instance for all the components. So remove the service from component level and add at the root level of application.

@NgModule({ declarations: [ AppComponent, CustomDirective, NgNifDirective, Comp1Component, Comp2Component ], imports: [ BrowserModule, FormsModule, HttpModule, CommonModule ], providers:[NumListService,LoggerService], bootstrap: [AppComponent] }) export class AppModule { }

After making all the above changes now if you add a value for “Comp1” it will also show in “Comp2” list and also vice versa. The reason is that now our service is providing a single instance for the both components.

Let’s take an example of nested services. We create a new service and use this service in already existing services. Use “ng generate service logger” command to create logger service.

Below is the code of logger service,

import { Injectable } from '@angular/core' ; @Injectable() export class LoggerService { constructor() { } log(name:string){ console.log( "This is " +name+ " Method" ); } }

In logger service, we add the “log” method that will display the name of calling method. Now we need to use this service in another service so register the logger service at root level of the application.

import { BrowserModule } from '@angular/platform-browser' ; import { NgModule } from '@angular/core' ; import { FormsModule } from '@angular/forms' ; import { HttpModule } from '@angular/http' ; import { CommonModule } from '@angular/common' ; import { AppComponent } from './app.component' ; import { CustomDirective } from './custom.directive' ; import { NgNifDirective } from './ng-nif.directive' ; import { Comp1Component } from './comp1/comp1.component' ; import { Comp2Component } from './comp2/comp2.component' ; import {NumListService} from './num-list.service' ; import {LoggerService} from './logger.service' @NgModule({ declarations: [ AppComponent, CustomDirective, NgNifDirective, Comp1Component, Comp2Component ], imports: [ BrowserModule, FormsModule, HttpModule, CommonModule ], providers:[NumListService,LoggerService], bootstrap: [AppComponent] }) export class AppModule { }

Now inject logger service in constructor of the “num-list” service and call the “log” method of logger service.

import { Injectable } from '@angular/core' ; import {LoggerService} from './logger.service' ; export class NumListService { list:number[]=[]; constructor( private loggerServcie:LoggerService) { } public addNum(num:number){ this .list.push(num); this .loggerServcie.log( "addNum" ); } public getList(){ this .loggerServcie.log( "getList" ); return this .list; } }

After making all above changes now refresh the page, when page will reload we get the following error in console.

To resolve this error, now add the “@injectabel()” metadata in ”num-list” service. Reason is that in Angular 2 if we are using any injectable object in a service then we need to define the “injectable” meta data in host service class. So add the “Injectable” meta data in “num-list” service.

import { Injectable,Inject } from '@angular/core' ; import {LoggerService} from './logger.service' ; @Injectable() export class NumListService { list:number[]=[]; constructor( private loggerServcie) { } public addNum(num:number){ this .list.push(num); this .loggerServcie.log( "addNum" ); } public getList(){ this .loggerServcie.log( "getList" ); return this .list; } }

Now, everything works fine and we get messages in web console.

In previous examples we used the @Injectable decorator to allow “num-list” class to use an injectable service. We have another way of using it so that we can achieve same goal. Now we discuss the “@inject()” decorator, @Inject() is a manual mechanism for letting Angular know that a parameter must be injected. You can use this as below.

import { Injectable,Inject } from '@angular/core' ; import {LoggerService} from './logger.service' ; export class NumListService { list:number[]=[]; constructor(@Inject(LoggerService) private loggerServcie) { } public addNum(num:number){ this .list.push(num); this .loggerServcie.log( "addNum" ); } public getList(){ this .loggerServcie.log( "getList" ); return this .list; } }

In the above code, we told Angular to inject the “loggerServcie” for this service. So now, we don’t need to define the “@Injectable” at class level.

Conclusion

In this article, we learned about the Dependency Inject and Services in Angular 2. In the next article we cover another topic in Angular 2.