Angular employs a hierarchical arrangement of injectors to manage the creation and dependencies of objects. The primary role of an injector is to produce an instance of a specific class or service and supply it to other segments of the application that rely on it.
The Angular Dependency Injection (DI) functions by enrolling services and other dependencies with an injector, which it then injects into components, services, and other classes that require them. Upon creating an instance of a service, the injector is also responsible for producing any dependencies that the service necessitates.
Modularity: Using DI simplifies dividing our code into more manageable and reusable pieces that can be evaluated separately.
Testability: It helps in the unit testing of our code.
Maintainability: The use of DI enhances the adaptability of our code and makes it simpler to modify since it reduces the degree of interdependence between various components of the application.
To use dependency injection, we first import Injectable
and use this Injectable
before the service, component, or class we want to inject.
import { Injectable } from '@angular/core';@Injectable({providedIn: 'root'})
Suppose we have a service called CustomerService
that provides customer information to our application. We also have a component called AllCustomerComponent
that displays a list of customers. We want to inject the CustomerService
into the AllCustomerComponent
to display the list of customers.
To create the CustomerService
, we must import the necessary modules and then create the service class. The CustomerService
class would have a method getCustomers()
that retrieves the list of customers:
import { Injectable } from '@angular/core';@Injectable({providedIn: 'root'})export class CustomerService {getCustomers() {return [{ id: 1, name: 'Hamza' },{ id: 2, name: 'Ali' },{ id: 3, name: 'Shahroz' },{ id: 4, name: 'Sara' },{ id: 5, name: 'Ahsan' }];}}
Next, we would create the AllCustomerComponent
and inject the CustomerService
into it using the constructor. In the ngOnInit()
lifecycle hook, the getCustomers()
method of the CustomerService
is called to retrieve the list of customers and assign it to the customers
property of the AllCustomerComponent
, as follows:
import { Component, OnInit } from '@angular/core';import { CustomerService } from './customer.service';@Component({selector: 'app-all-customers',template: `<h2>All Customers</h2><ul><li *ngFor="let customer of customers">{{ customer.name }}</li></ul>`})export class AllCustomersComponent implements OnInit {customers: any[];constructor(private customerService: CustomerService) {}ngOnInit() {this.customers = this.customerService.getCustomers();}}
In this example, the AllCustomerComponent
injects the CustomerService
using the constructor. The CustomerService
is then used to retrieve the list of customers and assign it to the customers
property of the AllCustomerComponent
. Here is an application that uses the code explained above.