What does the useFactory key do?
The useFactory key tells Angular:
"Create the dependency using my function (factory), not just through a class or a value."
Example:
ts
providers: [
{
provide: 'API_URL',
useFactory: () => {
return window.location.hostname === 'localhost'
? 'http://localhost:3000'
: 'https://api.example.com';
}
}
]Here Angular calls this function at startup and supplies its result (API_URL) as the dependency.
When this is needed:
- when the value needs to be computed dynamically;
- when it depends on conditions (environment, settings, a token, and so on);
- when the factory needs to use other dependencies internally.
Example with a dependency:
ts
providers: [
{
provide: ConfigService,
useFactory: (apiUrl: string) => new ConfigService(apiUrl),
deps: ['API_URL'] // dependencies for the factory
}
]Summary:
useFactory is a way to tell Angular: "get the dependency by calling my function, which decides on its own what to return."
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.