Thursday, August 22, 2024

Understanding Angular Dependency Injection

Angular Dependency Injection

Dependency Injection (DI) is a design pattern used to implement IoC (Inversion of Control), allowing a class to receive its dependencies from an external source rather than creating them itself. Angular’s DI system is a powerful feature that makes it easy to manage dependencies and promote code reusability and testability.

How Dependency Injection Works in Angular?

In Angular, DI is used to provide components, services, and other classes with the dependencies they need. The Angular injector is responsible for creating and managing these dependencies. Here’s a step-by-step explanation of how DI works in Angular:

  • Providers: A provider is an object that tells the injector how to create a dependency. Providers can be registered at different levels (module, component, or service).
  • Injector: The injector is responsible for creating instances of dependencies and injecting them into the classes that need them.
  • Tokens:Tokens are used to uniquely identify a dependency. They can be class types, strings, or injection tokens.

Example: Using Dependency Injection in Angular

Let’s create a simple example to demonstrate how DI works in Angular.

Step 1: Create a Service

First, we’ll create a service that provides some data.

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

@Injectable({
  providedIn: 'root',
})
export class DataService {
  constructor() {}

  getData() {
    return ['Item1', 'Item2', 'Item3'];
  }
}

In this example, the DataService class is decorated with @Injectable, making it available for injection throughout the application.

Step 2: Inject the Service into a Component

Next, we’ll create a component and inject the DataService into it.

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

@Component({
  selector: 'app-data',
  template: `
    <h1>Data from Service</h1>
    <ul>
      <li *ngFor="let item of data">{{ item }}</li>
    </ul>
  `,
})
export class DataComponent implements OnInit {
  data: string[];

  constructor(private dataService: DataService) {}

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

In this example, the DataComponent class has a dependency on DataService. The DataService is injected into the component's constructor, and its getData method is called to retrieve data.

Step 3: Register the Service in a Module (if not using providedIn: 'root')

If you are not using the providedIn: 'root' syntax, you need to register the service in a module.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { DataComponent } from './data.component';
import { DataService } from './data.service';

@NgModule({
  declarations: [AppComponent, DataComponent],
  imports: [BrowserModule],
  providers: [DataService],
  bootstrap: [AppComponent],
})
export class AppModule {}

In this example, the DataService is registered in the providers array of the AppModule.

Benefits of Dependency Injection

  • Reusability: Services can be reused across different components.
  • Testability: Dependencies can be easily mocked or replaced in unit tests.
  • Maintainability: Dependencies are managed in a centralized way, making the codebase easier to maintain.

Happy coding!! 😊

No comments:

Post a Comment

^ Scroll to Top