Angular, InjectionToken is a special type of object that is used to create custom tokens for dependency injection

 1. Custom Dependencies: If you need to provide a non-class dependency (like a string, number, or object), InjectionToken is used to create a unique token that Angular can use in the dependency injection system.

2. Avoid Conflicts: InjectionToken helps prevent conflicts in the DI system by providing a unique identifier for your custom dependencies, as opposed to relying on strings or class names.

3. Configuration and Constants: You can use InjectionToken to inject configuration values or constant objects into components or services.

Example of using 

InjectionToken:

  1. Creating an Injection Token:

    typescript

    import { InjectionToken } from '@angular/core'; export const API_URL = new InjectionToken
  2. Providing the Token in an Angular Module: In your module's providers array, you can provide a value for the token.
import { NgModule } from '@angular/core';
import { API_URL } from './tokens';

@NgModule({
  providers: [
    { provide: API_URL, useValue: 'https://api.example.com' }
  ]
})
export class AppModule { }

3. Injecting the Token into a Component or Service: Now you can inject the token into your services or components.

import { Component, Inject } from '@angular/core';
import { API_URL } from './tokens';

@Component({
  selector: 'app-api-consumer',
  template: `API URL: {{ apiUrl }}`
})
export class ApiConsumerComponent {
  constructor(@Inject(API_URL) public apiUrl: string) {}
}

No comments:

Post a Comment

The differences between Angular SSR (Server-Side Rendering) and Angular SSG (Static Site Generation) can be summarized as follows

  1.  When HTML is Generated SSR : HTML is dynamically generated  on each request  by the server. The server processes the request, fetches ...

Best for you