What is useFactory in Angular: Simple Explanation and Example
useFactory in Angular is a way to tell the dependency injector how to create a service or value using a factory function. Instead of providing a class or value directly, useFactory lets you run a function that returns the object to inject, allowing more control and customization.How It Works
Imagine you want to bake a cake, but instead of buying a ready-made cake, you want to follow a recipe that can change based on the ingredients you have. useFactory works like that recipe in Angular's dependency injection system. It lets you provide a function that creates the service or value you need, rather than just giving Angular a fixed class or value.
This factory function can use other services or data to decide what to return. Angular calls this function when it needs to inject the service, so you get a fresh or customized object each time or a shared one depending on your setup.
It’s like having a smart helper who knows how to build exactly what you need on demand, making your app more flexible and easier to configure.
Example
This example shows how to use useFactory to create a service that depends on a configuration value.
import { Injectable, InjectionToken, inject } from '@angular/core'; // Define a token for configuration export const API_URL = new InjectionToken<string>('API_URL'); // Factory function that returns a service object export function apiServiceFactory() { const url = inject(API_URL); return { getData: () => `Fetching data from ${url}` }; } // Provide the service using useFactory export const ApiServiceProvider = { provide: 'ApiService', useFactory: apiServiceFactory, deps: [API_URL] }; // Usage in a component import { Component, Inject } from '@angular/core'; @Component({ selector: 'app-root', template: `<p>{{ message }}</p>`, providers: [ { provide: API_URL, useValue: 'https://api.example.com' }, ApiServiceProvider ] }) export class AppComponent { message: string; constructor(@Inject('ApiService') private apiService: any) { this.message = this.apiService.getData(); } }
When to Use
Use useFactory when you need to create a service or value dynamically based on some logic or external data. For example:
- When the service depends on configuration values that are not known until runtime.
- When you want to create different instances based on conditions.
- When you want to combine multiple dependencies to build a single object.
This approach is helpful in apps that need flexible setup, like switching APIs, feature toggles, or creating mock services for testing.
Key Points
useFactorylets you provide a factory function to create a service or value.- The factory function can inject other dependencies using
depsorinject(). - It gives you flexibility to customize how services are created.
- Commonly used for dynamic configuration or conditional service creation.
- Works well with Angular's dependency injection system for clean, testable code.
Key Takeaways
useFactory allows Angular to create services using custom factory functions.