Thursday, August 22, 2024

Understanding @Injectable and @Inject Decorators in Angular

@Injectable and @Inject in Angular

In Angular, decorators are used to attach metadata to classes, methods, properties, and parameters. Two commonly used decorators are @Injectable and @Inject. While they might seem similar, they serve different purposes. Let’s dive into their differences and see how they are used with examples.

@Injectable Decorator

The @Injectable decorator is used to mark a class as available for dependency injection. It tells Angular's dependency injection system that the class can be injected as a dependency into other classes.

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

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

  getData() {
    return ['Data1', 'Data2', 'Data3'];
  }
}

In this example, the DataService class is decorated with @Injectable, making it available for injection throughout the application. The providedIn: 'root' syntax ensures that the service is a singleton and available application-wide.

@Inject Decorator

The @Inject decorator is used to manually specify a dependency to be injected. This is particularly useful when you need to inject a dependency that is not automatically resolved by Angular's dependency injection system, such as when using tokens or when the type information is lost due to minification.

Example:
import { Component, Inject } from '@angular/core';
import { DataService } from './data.service';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-root',
  template: `<h1>Angular @Inject Example</h1>`,
})
export class AppComponent {
  constructor(
    private dataService: DataService,
    @Inject(DOCUMENT) private document: Document
  ) {
    console.log(this.dataService.getData());
    console.log(this.document.title);
  }
}

In this example, the AppComponent class has two dependencies: DataService and Document. The DataService is injected automatically because it is marked with @Injectable. However, the Document object is injected using the @Inject decorator with the DOCUMENT token, which is provided by Angular's common module.

Key Differences

  • Purpose: @Injectable is used to mark a class as injectable, while @Inject is used to specify a particular dependency to be injected.
  • Usage: @Injectable is applied to classes, whereas @Inject is applied to constructor parameters.
  • Automatic Injection: @Injectable allows Angular to automatically resolve and inject dependencies, while @Inject is used for manual injection when automatic resolution is not possible.

Happy coding!! 😊

No comments:

Post a Comment

^ Scroll to Top