0 votes
in Angular by

Explain the concept of Dependency Injection?

1 Answer

0 votes
by
Dependency injection is an application design pattern which is implemented by Angular.

It also forms one of the core concepts of Angular.

So what is dependency injection in simple terms?

Let’s break it down, dependencies in angular are nothing but services which have functionality. The functionality of a service, can be needed by various components and directives in an application. Angular provides a smooth mechanism by which we can inject these dependencies into our components and directives.

So basically, we are just making dependencies which are injectable across all components of an application.

Let’s understand how DI (Dependency Injection) works:

Consider the following service, which can be generated using: ng g service test

 import { Injectable } from '@angular/core';
     @Injectable({
       providedIn: 'root'
     })
     export class TestService {
       importantValue:number = 42;
       constructor() { }
       returnImportantValue(){
         return this.importantValue;
       }
     }    
 As one can notice, we can create injectable dependencies by adding the @Injectable decorator to a class.

We inject the above dependency inside the following component:   

 import { TestService } from './../test.service';
      import { Component, OnInit } from '@angular/core';

      @Component({
        selector: 'app-test',
        templateUrl: './test.component.html',
        styleUrls: ['./test.component.css']
      })
      export class TestComponent implements OnInit {
        value:number;
        constructor(private testService:TestService) { }

        ngOnInit() {
          this.value = this.testService.returnImportantValue();
        }
      }
 One can see we have imported our TestService at the top of the page. Then, we created an instance inside the constructor of the component and implemented the returnImportantValue function of the service.

From the above example, we can observe how angular provides a smooth way to inject dependencies in any component.
...