0 day streak
javascript / expert
Snippet

Advanced Dependency Injection with InjectionToken Factories

InjectionToken factories allow for dynamic, environment-aware dependency resolution at the configuration level. This encapsulates complex instantiation logic (like feature toggles or environment checks) directly within the token, keeping components clean and testable.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
export interface StorageStrategy {
save(key: string, value: any): void;
}
export const STORAGE_STRATEGY = new InjectionToken<StorageStrategy>('StorageStrategy', {
providedIn: 'root',
factory: () => {
const isSupported = typeof window !== 'undefined' && !!window.localStorage;
return isSupported ? inject(LocalStorageStrategy) : inject(MemoryStorageStrategy);
}
});
angular
Breakdown
1
new InjectionToken<StorageStrategy>(...)
Creates a unique lookup key for the dependency injection system.
2
factory: () => { ... }
Defines the logic to resolve the implementation at runtime.
3
inject(LocalStorageStrategy)
Utilizes the functional inject() to retrieve other dependencies within the factory.