AppDividend
Latest Web Development Tutorials

Angular Dependency Injection Tutorial Example

Dependency Injection in Angular

287

Angular Dependency Injection is today’s main topic. Dependency injection is an important application design pattern. Angular has its own dependency injection framework, and you really can’t build an Angular application without it. It’s used so widely that almost everyone just calls it DI.

Angular Dependency Injection

First, we will take an example of what is the scenario, where we do not use any DI pattern.

Here, I am describing the example as a basic dependency injection.
Advance Angular Dependency Injection is in the next tutorial.

Example

Let us take an example of a Computer. The computer consists of following things.

  1. Monitor
  2. CPU
  3. Keyboard

So to complete the computer, we need those three things.

In this example, we need to require total four classes to build a fully functional computer.

  1. Computer class
  2. Monitor class
  3. CPU class
  4. Keyboard class

Without DI(Dependency Injection)

First, create four classes. All Four classes are in the src  >>  app directory.

Make Monitor.ts class.

// Monitor.ts

export class Monitor {
     public monitorNo = 2;
}

Next Keyboard.ts class.

// Keyboard.ts

export class Keyboard {
    public keyboardNo = 1;
}

Make CPU.ts class.

Related Posts
1 of 3
// CPU.ts

export class CPU {
    public cpuNo = 3;
}

Finally, make Computer.ts class.

// Computer.ts

import { Monitor } from './Monitor';
import { CPU } from './CPU';
import { Keyboard } from './Keyboard';

export class Computer {
 
  public monitor: Monitor;
  public cpu: CPU;
  public keyboard: Keyboard;
 
  constructor() {
    this.monitor = new Monitor();
    this.cpu = new CPU();
    this.keyboard = new Keyboard();
  }
 public description = 'This Matrix computer';
  complete() {
    return `${this.description} has ` +
      `${this.monitor.monitorNo} monitors, ${this.cpu.cpuNo} cpus and, ${this.keyboard.keyboardNo} keyboard.`;
  }
}

To complete the Computer class, we need to import all three classes here and make one fully functional Matrix computer.



Now, here we have created three classes instances in the constructor of Computer class.

Note that, Computer class is totally dependent on these three classes. Otherwise, it will not complete the computer.

We are creating the instances in the constructor. So monitors, cpus, and keyboard are not decoupled from the Computer class.

Finally, to work this example, we need to change the app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
import { Computer } from './Computer';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
	public computer: Computer;

	constructor(){
		this.computer = new Computer();
	}
  makeComputer(){
  	return this.computer.complete();
  }
}

And to change the view, edit the app.component.html

<!--The whole content below can be removed with the new code.-->
<div style="text-align:center">
  <h1>
      {{makeComputer()}}!!
  </h1>
</div>

Output

Save this file and type the following command.

ng serve
Note: I am using Angular CLI for quick configuration.
You can see the String like This Matrix computer has 2 monitors, 3 cpus, and 1 keyboard.!!

Example With Dependency Injection(DI)

If we are using Dependency Injection then, we do not need to create the instances in the constructor.

First, we need to provide all the dependencies to the app.module.ts class.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { Monitor } from './Monitor';
import { CPU } from './CPU';
import { Keyboard } from './Keyboard';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [Monitor, CPU, Keyboard],
  bootstrap: [AppComponent]
})
export class AppModule { }

In providers array, we need to provide all three dependencies.

Then, In the Computer.ts class, inject those dependencies into Computer’s constructor.

// Computer.ts

import { Monitor } from './Monitor';
import { CPU } from './CPU';
import { Keyboard } from './Keyboard';

export class Computer { 
 constructor(public monitor: Monitor, public cpu: CPU, public keyboard: Keyboard) {}
 public description = 'This Matrix computer';
  complete() {
    return `${this.description} has ` +
      `${this.monitor.monitorNo} monitors, ${this.cpu.cpuNo} cpus, and ${this.keyboard.keyboardNo} keyboard.`;
  }
}

Finally, modify the app.component.ts file.


// app.component.ts

import { Component } from '@angular/core';
import { Computer } from './Computer';
import { Monitor } from './Monitor';
import { CPU } from './CPU';
import { Keyboard } from './Keyboard';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
public computer: Computer;	
constructor(){
	this.computer = new Computer(new Monitor(), new CPU(), new Keyboard());
}
 makeComputer(){
  	return this.computer.complete();
  }
}

So, we have passed the argument at the time of creation of Computer instance.

When computer instance is created at that time, also all the other instances of other classes are also created.

After, save this file, the output will be the same as previous one.

Basic Angular Dependency Injection Tutorial Example is over.

 

Leave A Reply

Your email address will not be published.