Logo

dev-resources.site

for different kinds of informations.

Angular Dependency Injection

Published at
6/29/2022
Categories
angular
dependency
injection
Author
bipon68
Categories
3 categories in total
angular
open
dependency
open
injection
open
Author
7 person written this
bipon68
open
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", "[email protected]"]
  info2: string[] = ["Simon Gomez", "E321", "[email protected]"]
  info3: string[] = ["Bipon Biswas", "E123", "[email protected]"]

  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

dependency Article's
30 articles in total
Favicon
Ore: Advanced Dependency Injection Package for Go
Favicon
vcpkg - how to modify dependencies
Favicon
CocoaPods is in Maintenance Mode
Favicon
Safely restructure your codebase with Dependency Graphs
Favicon
Understanding Dependencies in Programming
Favicon
A zoom installer script for linux
Favicon
Loose Coupling and Dependency Injection (DI) principle
Favicon
Dependency Injection in swift
Favicon
Dependency relation in AWS CDK
Favicon
CORS how to enable them in .NET?
Favicon
Angular Dependency Injection
Favicon
Dependency management made easy with Dependabot and GitHub Actions
Favicon
Jetpack compose โ€” Dependency injection with Dagger/HILT
Favicon
Dependencies in node project
Favicon
Fixing vulnerabilities found in a dependency tree
Favicon
How to create your own dependency injection framework in Java
Favicon
Reduzindo a quantidade de Branchs na criaรงรฃo de Objetos com uma estrutura plugรกvel
Favicon
NodeJs - Dependency injection, make it easy
Favicon
A Step by Step Guide to ASP.NET Core Dependency Injection
Favicon
The Basics of Dependency Maintenance in NPM/yarn
Favicon
The troubles of modern software dependency management and what to do about them
Favicon
Loose Coupling Basics
Favicon
Correctly defining CDK dependencies in L3 constructs
Favicon
What dependency hell looks like, and how to avoid it
Favicon
How to create your own dependency injection framework in Java
Favicon
Dependency Inversion Principle in Swift
Favicon
Angular: Create a custom dependency injection
Favicon
Dagger with a Hilt
Favicon
How to find what is the dependency of a function, class, or variable in ES6 via AST
Favicon
Data Dependency Graph

Featured ones: