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
:
Creating an Injection Token:
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