Middle+
How is the Dependency Inversion principle implemented in Angular? What is InjectionToken?
sobes.tech AI
Answer from AI
In Angular, the Dependency Inversion principle is implemented through the Dependency Injection (DI) mechanism. Instead of components creating dependencies themselves, they receive them from outside, which increases modularity and testability.
InjectionToken is a special class used to create a unique token for DI, especially when you need to inject a value or object that is not a class (for example, a string, configuration, or interface). This allows Angular to precisely identify what needs to be injected.
Example of using InjectionToken:
import { InjectionToken } from '@angular/core';
export const API_URL = new InjectionToken<string>('apiUrl');
// In module providers
providers: [
{ provide: API_URL, useValue: 'https://api.example.com' }
]
// In a component or service
constructor(@Inject(API_URL) private apiUrl: string) {}