Dependency Injection Pattern

Dependency Injection (DI) is a design pattern widely used in Angular (as well as in many other frameworks) to facilitate loose coupling between components and services.

In Angular, DI allows you to inject dependencies (services or other objects) into components, directives, pipes, and other Angular classes.

Here's an example of how Dependency Injection works in Angular:

Suppose you have a service called DataService that provides data to your application:

// data.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  getData() {
    return ['item1', 'item2', 'item3'];
  }
}

Now, let's say you have a component called ListComponent that needs to use this service to fetch data:

// list.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-list',
  template: `
    <ul>
      <li *ngFor="let item of items">{{ item }}</li>
    </ul>
  `
})
export class ListComponent implements OnInit {
  items: string[];

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.items = this.dataService.getData();
  }
}

In this code:

  1. We import the DataService into the ListComponent.

  2. We inject the DataService into the ListComponent constructor. This is where the magic of DI happens. Angular's DI system knows how to create instances of DataService and provides it to the ListComponent when it's instantiated.

  3. In the ngOnInit lifecycle hook, we use the DataService to fetch data and assign it to the items property.

With Dependency Injection, the ListComponent doesn't need to know how to create an instance of DataService or where it comes from. Angular's injector takes care of providing the DataService instance to the ListComponent.

This pattern makes our code more modular, reusable, and easier to test because components and services are decoupled.

Additionally, it allows for easy swapping of dependencies, for example, if you wanted to mock DataService in unit tests.

Last updated