What is InjectionToken and how it is use in Angular?

In Angular, an InjectionToken is a type of token that can be used as a key for a service or value in the Angular Dependency Injection system. It is used to provide a way to configure or configure a dependency in a more flexible way than simply using a class or a string as a key.

When you create an InjectionToken, you can pass a default value as an argument, which will be used if the token is not provided elsewhere. For example:

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

export const MY_TOKEN = new InjectionToken<string>('MyToken', {
  providedIn: 'root',
  factory: () => 'Default value'
});

In this example, MY_TOKEN is an InjectionToken with a default value of “Default value”. The factory function is used to provide a default value if the token is not found in the injection context.

You can use the InjectionToken in your component or service by including it as a provider:

import { Inject, InjectionToken } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor(@Inject(MY_TOKEN) private myToken: string) {
    console.log(myToken);
  }
}

In this example, the MyService class uses the MY_TOKEN InjectionToken as a dependency by using the @Inject decorator. If the MY_TOKEN is provided in the injection context, its value will be used, otherwise the default value specified in the factory function of the MY_TOKEN InjectionToken will be used.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *