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 a functionality. 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 in 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();

        }

Related questions

0 votes
asked Jan 30 in Dot Net by GeorgeBell
0 votes
asked Nov 24, 2019 in Angular by rajeshsharma
...