Simple Introduction to Dependency Injection in Angular

Dependency Injection – Important Application Design Pattern across all frameworks.

Angular provide its own DI Framework, used in the design of Angular Applications to increase efficiency and modularity. Dependency can be in the form of service or object for the class to perform its task.DI is a coding pattern where the class refer other external sources for dependency rather than self-creating.If we talk about DI Framework in Angular, it provides declared dependencies to a class when that class is instantiated.

Lets understand this by Example

Example without DI

Student Class 
export class Student {
 studentid: number;
  studentname: string;
  studentclass: number;
}

Student Array
   export const StudentList: Student[] = [
       { studentid: 11, studentname:'Ravi', studentclass: 'IX' },
       { studentid: 12, studentname:'Ram', studentclass: 'X' },
      { studentid: 13, studentname:'Raghu', studentclass: 'VII' },
      { studentid: 14, studentname:'Ankit', studentclass: 'VIII' },
      { studentid: 15, studentname:'Rahul', studentclass: 'X' }
]; 
To fetch the list of Students we do use the below component. 
export class StudentListComponent {
  students = StudentList;
}  


This approach works for prototyping, but is not robust or maintainable. As soon as we try to test this component or get students from a remote server, we have to change the implementation of StudentListComponent and replace every use of the StudentList data.

Lets make it flexible using DI Framework

We are going to get the data from injectable service class to the component for displaying purpose. This is what DI helps in.
Lets create an injectable service class which will provide the list of students and register that class as a provider of that service.

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root',
})
export class StudentService {
 // constructor() { }
getStudentList() { return StudentList; }
}


The @Injectable() decorator has the providedIn metadata option, where you can specify the provider of the decorated service class with the rootvinjector, or with the injector for a specific NgModule.
Now we have created the class which provides service. @Injectable decorator specifies that it can be injected. To inject it, we need to configure the Angular Injector with a provider of this service.
In order for StudentListComponent to get students from StudentService, it needs to ask for StudentService to be injected, rather than creating it’s own StudentService instance with new.

export class StudentListComponent {
  students: Student[];
  constructor(studentService: StudentService) {
    this.students = studentService.getStudentList();
  }}

So the above component doesn’t depend on where the service comes from, it can be in appmodule also.

Points to remember :

  • Injectors are inherited, which means that if a given injector can’t resolve a dependency, it asks the parent injector to resolve it.
  • A component can get services from its own injector, from the injectors of its component ancestors, from the injector of its parent NgModule, or from the root injector.
  • Services are singletons within the scope of an injector, i.e there is only one instance in the whole app unless we are configuring another provider with child injector.
  • Service can have their own dependencies. One Service can inject other service for logging or other activities.

We will be covering more about DI in coming sections ….. Keep watching

Leave a Reply

Your email address will not be published. Required fields are marked *