Loading...

Dependency Injection in Angular

Dependency Injection (DI) is a design pattern in Angular that allows you to provide dependencies to a class rather than having the class create them itself. This makes your code more modular, testable, and maintainable.

In simple terms, DI means that instead of a class creating its own dependencies, these dependencies are "injected" into the class from an external source. This promotes loose coupling and makes it easier to manage dependencies.

Why Use Dependency Injection?

  • Modularity: Components and services become more independent.
  • Testability: Dependencies can be easily mocked or replaced for testing.
  • Reusability: Services can be reused across multiple components.
  • Maintainability: Code becomes easier to understand and manage.

How Dependency Injection Works in Angular

Angular uses a hierarchical dependency injection system. When you request a dependency, Angular looks for a provider in the current injector and its parent injectors.

1. Creating a Service

First, create a service that will be injected as a dependency.

Example: Data Service


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

                @Injectable({
                    providedIn: 'root'
                        })
    export class DataService {
      getData(): string[] {
        return ['Item 1', 'Item 2', 'Item 3'];
      }
    }
    

Explanation:

  • @Injectable({ providedIn: 'root' }): Marks the class as injectable and makes it available throughout the application.
  • getData(): A method that returns an array of strings.

2. Injecting the Service into a Component

To use the service in a component, inject it into the component's constructor.

Example: My Component


    import { Component, OnInit } from '@angular/core';
    import { DataService } from './data.service';
    @Component({
      selector: 'app-my-component',
      template: '<ul><li* ngFor = "let item of items" >{{item}}</li></ul>'
    })
    export class MyComponent implements OnInit {
      items: string[];

      constructor(private dataService: DataService) {}

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

Explanation:

  • constructor(private dataService: DataService): Injects the DataService into the component.
  • ngOnInit(): Calls the getData() method of the injected service.

3. Providing the Service in a Module

While providedIn: 'root' handles this for most services, you can also provide services at the module level.

Example: Providing in a Module


    import { NgModule } from '@angular/core';
    import { DataService } from './data.service';
    import { MyComponent } from './my.component';

                @NgModule({
                    declarations: [MyComponent],
      providers: [DataService],
      exports: [MyComponent]
    })
    export class MyModule {}
    

Explanation:

  • providers: [DataService]: Registers the DataService with the module's injector.
  • This makes the service available to all components within the module.

4. Injecting into another Service

Services can also have dependencies injected into them.

Example: Logging Service with Data Service


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

                @Injectable({
                    providedIn: 'root'
                        })
    export class LoggingService {
      constructor(private dataService: DataService) {}

      logData(): void {
        const data = this.dataService.getData();
        console.log('Logging data:', data);
      }
    }
    

Explanation:

  • constructor(private dataService: DataService): Injects the DataService into the LoggingService.
  • logData(): Uses the injected DataService to retrieve data.

Key Points

  • Dependency Injection is a design pattern that provides dependencies to a class.
  • Use the @Injectable decorator to mark a class as injectable.
  • Inject dependencies into a class's constructor.
  • Use providedIn: 'root' to make services available throughout the application.
  • Services can also have dependencies injected into them.

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!