Monday, September 2, 2024

Hierarchical Dependency Injection in Angular

Hierarchical Dependency Injection in Angular

Hierarchical Dependency Injection (DI) in Angular is a powerful feature that allows you to control the scope and lifetime of services. It enables you to create a hierarchy of injectors, where each injector can provide its own set of dependencies. This hierarchy mirrors the component tree, allowing for fine-grained control over which services are available to which parts of your application.

How Hierarchical Dependency Injection Works?

In Angular, every component has its own injector, and these injectors form a hierarchy. The root injector is created when the application starts, and child injectors are created for each component. When a component requests a dependency, Angular starts at the component’s injector and works its way up the hierarchy until it finds a provider for the requested dependency.

Example

Let’s look at an example to understand how hierarchical DIworks.

Step 1: Create a Service

First, we’ll create a simple service.

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

@Injectable({
  providedIn: 'root',
})
export class LoggerService {
  log(message: string) {
    console.log(message);
  }
}
Step 2: Create Components

Next, we’ll create a parent component and a child component .

import { Component } from '@angular/core';
import { LoggerService } from './logger.service';

@Component({
  selector: 'app-parent',
  template: `
    <h1>Parent Component</h1>
    <app-child></app-child>
  `,
  providers: [LoggerService],
})
export class ParentComponent {
  constructor(private logger: LoggerService) {
    this.logger.log('Parent Component Initialized');
  }
}

@Component({
  selector: 'app-child',
  template: `<h2>Child Component</h2>`,
})
export class ChildComponent {
  constructor(private logger: LoggerService) {
    this.logger.log('Child Component Initialized');
  }
}

In this example, the ParentComponent provides the LoggerService. The ChildComponent does not provide the LoggerService, so it will use the instance provided by the ParentComponent.

Step 3: Register Components in a Module

Finally, we’ll register the components in a module.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ParentComponent } from './parent.component';
import { ChildComponent } from './child.component';

@NgModule({
  declarations: [AppComponent, ParentComponent, ChildComponent],
  imports: [BrowserModule],
  bootstrap: [AppComponent],
})
export class AppModule {}

Key Points

  • Injector Hierarchy: Each component has its own injector, forming a hierarchy that mirrors the component tree.
  • Provider Scope: Providers can be registered at different levels (root, module, component), controlling the scope and lifetime of services.
  • Dependency Resolution: Angular starts at the component’s injector and works its way up the hierarchy to resolve dependencies.

Benefits of Hierarchical Dependency Injection

  • Scoped Services: You can create services that are scoped to specific parts of your application, improving modularity and encapsulation.
  • Optimized Performance: By limiting the scope of services, you can reduce memory usage and improve performance.
  • Flexible Configuration: Different parts of your application can use different configurations of the same service.

Hierarchical DI is a powerful feature that allows you to build scalable and maintainable Angular applications by providing fine-grained control over service instances and their lifetimes.

Happy coding!! 😊

No comments:

Post a Comment

^ Scroll to Top