DEV Community

Bipon Biswas
Bipon Biswas

Posted on

1 1

Angular Dependency Injection

Objective: In this article, you will know dependency injection concept, custom dependency injection in Angular.

Pre-requisite Prior to completing this article, you should have already installed all pre-requisite tooling including: Visual Studio Code, Node Package Manager (NPM), Node, Angular CLI.

Dependency Injection

Consider all these components performing common task like accessing the database, rendering images on the view etc.

  • to avoid rewriting of code, Angular Service can be used
  • these service can then injected into the components that require that service
  • Dependency Injection or DI keeps the code flexible, testable and mutable
  • Classes can inherit external logic without knowing how to create it
  • DI is benefits directive, pipes and components

Normally, components are used to ensure a good user experience.

  • In order to execute tasks, using Service is ideal.
  • A component can delegate tasks like fetching data from the server, validating user input, or logging directly to the console to the Service.

Use Case

  • Create a Service that performs the task of displaying an employee list
  • Inject the service into the class using Dependency Injection

At first create a component ng g c emp_info

Next create a service ng g s records

records.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class RecordsService {

  info1: string[] = ["John Doe", "E234", "john@gmail.com"]
  info2: string[] = ["Simon Gomez", "E321", "simon@gmail.com"]
  info3: string[] = ["Bipon Biswas", "E123", "bipon@gmail.com"]

  getInfo1(): string[]{
    return this.info1;
  }
  getInfo2(): string[]{
    return this.info2;
  }
  getInfo3(): string[]{
    return this.info3;
  }

  constructor() { }
}
Enter fullscreen mode Exit fullscreen mode

Let's go back to our component .ts file emp-info.component.ts

import { Component, OnInit } from '@angular/core';
import { RecordsService } from '../records.service';

@Component({
  selector: 'app-emp-info',
  templateUrl: './emp-info.component.html',
  styleUrls: ['./emp-info.component.css'],
  providers: [RecordsService]
})
export class EmpInfoComponent implements OnInit {

  infoReceived1: string[] = [];
  infoReceived2: string[] = [];
  infoReceived3: string[] = [];

  constructor(private rservice: RecordsService) { }

  ngOnInit(): void {
  }

  getInfoFromServiceClass1(){
    this.infoReceived1 = this.rservice.getInfo1();
  }
  getInfoFromServiceClass2(){
    this.infoReceived2 = this.rservice.getInfo2();
  }
  getInfoFromServiceClass3(){
    this.infoReceived3 = this.rservice.getInfo3();
  }

}
Enter fullscreen mode Exit fullscreen mode

Service are implemented with the help of Dependancy Injection.

What we need to do. At first import the Service into the emp-info.component.ts file.

Import Service

import { RecordsService } from '../records.service';
Enter fullscreen mode Exit fullscreen mode

emp-info.component.html

<button type="button" name="button" (click)="getInfoFromServiceClass1()">Employee1</button>
<ul>
    <li *ngFor="let info of infoReceived1" class="list-group-item">{{info}}</li>
</ul>

<button type="button" name="button" (click)="getInfoFromServiceClass2()">Employee2</button>
<ul>
    <li *ngFor="let info of infoReceived2" class="list-group-item">{{info}}</li>
</ul>

<button type="button" name="button" (click)="getInfoFromServiceClass3()">Employee3</button>
<ul>
    <li *ngFor="let info of infoReceived3" class="list-group-item">{{info}}</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

Create a three different button for different employees. And user click on the button the data is showing in the UI.

Import into app.component.html

<app-emp-info></app-emp-info>
Enter fullscreen mode Exit fullscreen mode

Employee list

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay