Provider Token vs Injection Token in Angular
Based on Angular documentation:
Provider token v17.angular.io/api/core/ProviderToken
Injection token angular.dev/api/core/InjectionToken
In Angular, Injection Token and Provider Token are related but not exactly the same. Let me explain:
---
Provider Token
A Provider Token is a general term referring to any token that identifies a dependency provider in Angular's dependency injection system. It can be:
1. Class (Type): A class is the most common provider token.
export class MyService { }
providers: [{ provide: MyService, useClass: MyService }]
2. String or Symbol: A string or symbol can act as a provider token.
providers: [{ provide: 'myStringToken', useValue: 'Some Value' }]
3. InjectionToken: A special token introduced for non-class-based dependencies.
---
Injection Token
An InjectionToken is a specific type of provider token used to define custom tokens for dependency injection. It allows you to specify dependencies that don't have a class or existing token.
It is type-safe and useful when injecting values like objects, strings, or configurations.
It is created using the InjectionToken class.
Example:
import { InjectionToken } from '@angular/core';
export const MY_TOKEN = new InjectionToken<string>('A custom token');
providers: [
{ provide: MY_TOKEN, useValue: 'My custom value' }
];
// Injecting it into a component or service
constructor(@Inject(MY_TOKEN) private value: string) {
console.log(this.value); // Outputs: My custom value
}
---
Relationship between the Two
An InjectionToken is a specific type of Provider Token.
A Provider Token can refer to classes, strings, symbols, or InjectionTokens.
In short: Every InjectionToken is a Prov
ider Token, but not every Provider Token is an InjectionToken.