Sub topic 6
Provider Recipes: useClass, useValue, useFactory, useExisting
This chapter assumes you know how to register a provider in a providers array and how to inject a dependency with inject(). Here you will learn the four recipes that tell an injector how to produce the value behind a token.
The shape of a provider
A provider is an object with two parts. The provide key is the token that consumers ask for. A recipe key says what the injector hands back. When you write a bare class such as providers: [CartService], Angular reads it as { provide: CartService, useClass: CartService }.
| Recipe | What the injector returns | Typical use |
|---|---|---|
| `useClass` | A new instance of the given class | Swap one implementation for another |
| `useValue` | The exact value you supply | Config objects, constants, test doubles |
| `useFactory` | Whatever the factory function returns | Choose or build the value at runtime |
| `useExisting` | The instance already registered under another token | Aliases: two tokens, one instance |
Each injector caches the result. The class is instantiated or the factory is called once per injector, and every later request gets the same value.
All four recipes in one setup
The file below defines an abstract Logger and two implementations, then uses each recipe once.
// logging.ts
import { Injectable, inject } from '@angular/core';
export class AppSettings {
debug = false;
}
export abstract class Logger {
abstract log(message: string): void;
}
export abstract class AuditLogger extends Logger {}
@Injectable()
export class ConsoleLogger extends Logger {
log(message: string): void {
console.log(`[app] ${message}`);
}
}
@Injectable()
export class SilentLogger extends Logger {
log(): void {}
}
export const loggingProviders = [
// useValue: hand over a ready-made object
{ provide: AppSettings, useValue: { debug: true } },
// useClass: register the concrete classes so the factory can inject them
{ provide: ConsoleLogger, useClass: ConsoleLogger },
SilentLogger,
// useFactory: decide at runtime, using inject() inside the factory
{
provide: Logger,
useFactory: () =>
inject(AppSettings).debug ? inject(ConsoleLogger) : inject(SilentLogger)
},
// useExisting: AuditLogger is an alias for whatever Logger resolved to
{ provide: AuditLogger, useExisting: Logger }
];// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { loggingProviders } from './app/logging';
bootstrapApplication(AppComponent, { providers: [loggingProviders] });Angular flattens nested arrays, so you can pass loggingProviders directly. Any component can now call inject(Logger) or inject(AuditLogger). Both calls return the same ConsoleLogger instance.
Common errors
- Confusing
useClasswithuseExisting.{ provide: AuditLogger, useClass: ConsoleLogger }creates a secondConsoleLoggerinstance. If the class holds state, the two copies drift apart. UseuseExistingwhen you need one shared instance under two tokens. - Forgetting a factory's own dependencies. The factory above calls
inject(ConsoleLogger). IfConsoleLoggeris not provided and is notprovidedIn: 'root', you getNullInjectorError: No provider for ConsoleLogger. - Mutating a
useValueobject. Every consumer receives the same object reference. A change made by one consumer is visible to all of them. Freeze config objects withObject.freezeif they should stay read-only. - Expecting a factory to rerun. The factory runs once per injector, so it is not a way to get a fresh value on every injection. Return a function from the factory if consumers need new values on demand.
- Calling
inject()asynchronously in a factory.inject()works only while the factory runs synchronously. A call inside asetTimeoutor after anawaitthrows. - Aliasing in a loop.
useExistingfrom A to B and from B back to A causes a cyclic dependency error.
Exercise
You register { provide: AuditLogger, useClass: ConsoleLogger } alongside { provide: Logger, useClass: ConsoleLogger }. A component injects both tokens and compares them with ===. What is the result, and what one change makes it true?
Show answer
The result is false, because each useClass provider creates its own ConsoleLogger instance. Change the AuditLogger provider to { provide: AuditLogger, useExisting: Logger } so both tokens resolve to the same instance.
Exercise
Write a provider for a Clock token (an abstract class with now(): number) that returns an object whose now() always returns 0 when AppSettings.debug is true, and Date.now() otherwise.
Show answer
{ provide: Clock, useFactory: () => inject(AppSettings).debug ? { now: () => 0 } : { now: () => Date.now() } }. The factory reads AppSettings through inject() while it runs synchronously, and the injector caches the object it returns.