0 day streak
javascript / intermediate
Snippet

Dynamic Dependency Injection with useFactory

The useFactory provider allows you to create a dependency dynamically based on other services or runtime conditions. It is ideal for complex instantiation logic that requires parameters from other providers.

snippet.js
javascript
1
2
3
4
5
6
7
export const APP_LOGGER_PROVIDER = {
provide: Logger,
useFactory: (config: ConfigService) => {
return config.isDev ? new ConsoleLogger() : new FileLogger();
},
deps: [ConfigService]
};
angular
Breakdown
1
useFactory: (config: ConfigService) => { ... }
A function that returns the desired implementation based on the config service.
2
deps: [ConfigService]
Specifies the dependencies to be injected as arguments into the factory function.