javascript / expert
Snippet
Dynamic Dependency Injection using Functional Factories
Angular's modern Dependency Injection allows defining providers directly within an `InjectionToken` using a factory. By using the `inject()` function inside the factory, you can dynamically resolve other dependencies at runtime. This pattern promotes clean, decoupled configurations and reduces boilerplate in the `AppConfig` or module definitions.
snippet.js
1
2
3
4
5
6
7
8
9
import { InjectionToken, inject } from '@angular/core';export const API_CONFIG = new InjectionToken<string>('ApiConfig', {providedIn: 'root',factory: () => {const env = inject(ENVIRONMENT_TOKEN);return env.production ? 'https://api.pro.com' : 'https://api.dev.com';}});
angular
Breakdown
1
factory: () => { ... }
Defines the logic to create the dependency value when requested.
2
const env = inject(ENVIRONMENT_TOKEN);
Uses the functional inject API to retrieve another token within the factory context.