Sub topic 6
Provider Recipes: useClass, useValue, useFactory, useExisting
This chapter assumes you know TypeScript classes and abstract classes, standalone components with bootstrapApplication, and the earlier chapters on @Injectable, inject(), and registering providers. You will learn the four provider recipes Angular offers. You will see what each one creates, when it runs, and how many instances it produces. You will also learn the mistakes that come up most often with each recipe.
What a provider recipe is
A provider is a pair of two things. The first is a token, the key a consumer asks for. The second is a recipe, the instructions the injector follows to produce a value for that key. When you write a bare class in a providers array, you are using a shorthand:
import { Injectable } from '@angular/core';
@Injectable()
export class ConsoleLogger {
log(message: string): void {
console.log(message);
}
}
// These two entries are equivalent:
export const shorthand = [ConsoleLogger];
export const longhand = [{ provide: ConsoleLogger, useClass: ConsoleLogger }];The provide key holds the token. The useClass, useValue, useFactory, or useExisting key holds the recipe. Each recipe answers one question differently: "How do I get the value the first time someone asks for this token?"
Whatever the recipe, an injector creates the value once, caches it, and hands every later consumer of that injector the cached result. The recipe controls how the value is made. It does not control how often, because that is always once per injector.
The four recipes at a glance
| Recipe | What the injector stores | When the value is made | Typical use |
|---|---|---|---|
| `useClass` | A new instance of the given class | On first injection | Swap one implementation for another |
| `useValue` | The exact object or primitive you pass | When your code evaluates the provider literal, before any injection | Configuration, constants, test doubles |
| `useFactory` | Whatever the factory function returns | On first injection | Decide at runtime, or build values that need setup |
| `useExisting` | Nothing new. It points at another token | Resolved on each lookup through the target token | Aliases, and exposing one instance under several types |
useClass: substitute an implementation
useClass tells the injector to call new on a class, resolving that class's own dependencies along the way. The token and the class can be different. That difference is the whole point of the recipe: consumers depend on the token, and you decide which class sits behind it.
An abstract class makes a good token. Unlike a TypeScript interface, an abstract class still exists at runtime, so Angular can use it as a lookup key.
import { Injectable } from '@angular/core';
export abstract class Logger {
abstract log(message: string): void;
}
@Injectable()
export class ConsoleLogger extends Logger {
log(message: string): void {
console.log(`[app] ${message}`);
}
}
@Injectable()
export class SilentLogger extends Logger {
log(): void {}
}
// Every consumer that calls inject(Logger) gets a ConsoleLogger.
export const loggingProviders = [{ provide: Logger, useClass: ConsoleLogger }];To switch the whole application to SilentLogger, you change one line. No consumer has to change.
Common errors with useClass
- Missing
@Injectable()on the class. If the class injects anything, Angular needs the factory that the decorator generates. Without it you get an error saying the class cannot be resolved. Decorate every class you pass touseClass, even when it currently has no dependencies. - Expecting a shared instance. Suppose you register
ConsoleLoggerand also{ provide: Logger, useClass: ConsoleLogger }. You now have two separate instances, one per token. If they hold state, the two copies drift apart. TheuseExistingsection below shows the fix. - Using an interface as the token.
{ provide: MyInterface, useClass: Impl }does not compile, because interfaces are erased at runtime. Use an abstract class or anInjectionToken, which the next chapter covers.
useValue: hand over a ready-made value
useValue stores exactly what you pass, by reference. Angular does not copy it, call it, or resolve dependencies inside it.
import { bootstrapApplication } from '@angular/platform-browser';
import { Component } from '@angular/core';
export abstract class FeatureFlags {
abstract readonly darkMode: boolean;
abstract readonly betaSearch: boolean;
}
@Component({
selector: 'app-root',
standalone: true,
template: `<p>App</p>`
})
export class AppComponent {}
bootstrapApplication(AppComponent, {
providers: [
{ provide: FeatureFlags, useValue: { darkMode: true, betaSearch: false } }
]
});Edge cases with useValue
- The value is evaluated eagerly. The object literal is built when the
providersarray is evaluated, usually at startup, even if nothing ever injects it. UseuseFactoryfor anything expensive. - Shared mutable references. Every consumer receives the same object. If one consumer mutates it, everyone sees the change. That includes other tests that reuse the same constant. Freeze shared config with
Object.freezeif it should not change. - Passing a class by mistake.
{ provide: Logger, useValue: ConsoleLogger }injects the constructor function, not an instance. Callinglogger.log(...)then fails at runtime. This mistake is easy to make and the compiler will not always catch it. undefinedandnullare legal values. Angular stores them without complaint. A consumer that expects an object getsnulland fails later, far from the cause.
useFactory: compute the value at runtime
useFactory calls a function the first time the token is requested and caches the return value. The factory runs in an injection context, so it can call inject() to read other dependencies.
import { Injectable, InjectionToken, inject } from '@angular/core';
export interface AppConfig {
apiUrl: string;
}
export const APP_CONFIG = new InjectionToken<AppConfig>('APP_CONFIG');
export abstract class Logger {
abstract log(message: string): void;
}
@Injectable()
export class ConsoleLogger extends Logger {
log(message: string): void {
console.log(message);
}
}
@Injectable()
export class SilentLogger extends Logger {
log(): void {}
}
export const loggerProviders = [
ConsoleLogger,
SilentLogger,
{
provide: Logger,
useFactory: () =>
inject(APP_CONFIG).apiUrl.includes('localhost')
? inject(ConsoleLogger)
: inject(SilentLogger)
}
];ConsoleLogger and SilentLogger are registered as well. The factory calls inject(ConsoleLogger), so that token must exist in this injector or one of its parents.
Older code declares dependencies with a deps array, and Angular passes them to the factory as arguments in order:
import { InjectionToken } from '@angular/core';
export interface AppConfig {
apiUrl: string;
}
export const APP_CONFIG = new InjectionToken<AppConfig>('APP_CONFIG');
export const API_BASE = new InjectionToken<string>('API_BASE');
export const apiProviders = [
{
provide: API_BASE,
useFactory: (config: AppConfig) => `${config.apiUrl}/v2`,
deps: [APP_CONFIG]
}
];Both forms work. The inject() form is easier to read and type-checks each dependency on its own, so prefer it in new code.
Common errors with useFactory
- Calling
inject()asynchronously. The injection context only exists while the factory body runs synchronously. A call toinject()inside asetTimeout, a.then(), or after anawaitthrowsNG0203. Read every dependency at the top of the factory and capture it in a local variable. - Expecting the factory to re-run. The factory runs once per injector. If you want a fresh value on every read, return a function or an object with a method, not the value itself.
- Side effects in the factory. The factory is lazy, so side effects such as opening a socket happen at an unpredictable moment: whenever something first injects the token. Keep setup that must run at startup in
provideAppInitializerinstead. - Missing return type. If the factory's return type does not match what consumers expect, TypeScript cannot warn you when the token is a class. Annotate the factory's return type explicitly.
useExisting: alias one token to another
useExisting creates no value. It tells the injector: "when someone asks for token A, look up token B and return that." Both tokens then resolve to the same instance.
The difference from useClass matters most for stateful services. The following spec shows it directly:
import { Injectable } from '@angular/core';
import { TestBed } from '@angular/core/testing';
export abstract class Logger {
abstract log(message: string): void;
}
@Injectable()
export class ConsoleLogger extends Logger {
readonly lines: string[] = [];
log(message: string): void {
this.lines.push(message);
}
}
describe('useClass vs useExisting', () => {
it('useClass creates a second instance', () => {
TestBed.configureTestingModule({
providers: [ConsoleLogger, { provide: Logger, useClass: ConsoleLogger }]
});
expect(TestBed.inject(Logger)).not.toBe(TestBed.inject(ConsoleLogger));
});
it('useExisting reuses the same instance', () => {
TestBed.configureTestingModule({
providers: [ConsoleLogger, { provide: Logger, useExisting: ConsoleLogger }]
});
expect(TestBed.inject(Logger)).toBe(TestBed.inject(ConsoleLogger));
});
});Typical uses:
- Migrating an API. Keep
OldLoggerworking while code moves toNewLogger:{ provide: OldLogger, useExisting: NewLogger }. - Exposing one instance under a narrower type. A store class can also be provided as a read-only abstract class, so some consumers only see the read methods.
- Letting a component expose itself. A component can declare
{ provide: ParentForm, useExisting: forwardRef(() => MyFormComponent) }in itsprovidersso that children can inject it through the abstract token.forwardRefis needed because the class is not yet defined at the point where its own decorator is evaluated.
Edge cases with useExisting
- The target must be provided.
useExistingdoes not register the target token. IfConsoleLoggeris not provided anywhere, injectingLoggerthrowsNG0201: No provider for ConsoleLogger. - Self-reference.
{ provide: Logger, useExisting: Logger }creates a cycle, and Angular reports a circular dependency error (NG0200). - The lookup starts from the injector where the alias is registered. If you register the alias in a component's
providers, the target is searched from that component's injector upward. That can find a different instance than you expected. Later chapters on the injector hierarchy explain how that search works.
Choosing between recipes
Consider who owns the value and how many instances there should be:
- Choose
useClasswhen consumers should get their own implementation, picked by configuration rather than logic. - Choose
useValuewhen the value already exists and has no dependencies, such as config objects, constants, and test fakes. - Choose
useFactorywhen choosing or building the value needs code: reading config, combining several dependencies, or wrapping a third-party object. - Choose
useExistingwhen two tokens must return the exact same instance.
Exercise
A team registers providers: [CartStore, { provide: CartReader, useClass: CartStore }]. Components that inject CartReader never see items added through CartStore. Why, and what one-word change fixes it?
Show answer
useClass makes the injector create a second, independent CartStore instance for the CartReader token, so the two tokens hold separate state. Change useClass to useExisting, so CartReader resolves to the same CartStore instance.
Exercise
This factory throws NG0203 on first use: useFactory: async () => { const http = await loadClient(); return new Api(http, inject(APP_CONFIG)); }. Explain the cause and rewrite the start of the factory so it works.
Show answer
inject() only works while the factory runs synchronously. After the await, the injection context is gone. Read the dependency first: useFactory: () => { const config = inject(APP_CONFIG); return loadClient().then(http => new Api(http, config)); }. Consumers then receive a Promise of Api, so type the token to match.
Exercise
You write { provide: Logger, useValue: ConsoleLogger }. The app compiles, but logger.log('hi') fails at runtime. What did the injector store, and which two recipes would give you a working instance?
Show answer
The injector stored the ConsoleLogger constructor function itself, not an instance, so log is not defined on it. Use { provide: Logger, useClass: ConsoleLogger }, or { provide: Logger, useValue: new ConsoleLogger() } if ConsoleLogger has no injected dependencies.