Sub topic 2
Registering Providers
This chapter assumes you know TypeScript classes and generics, standalone components, bootstrapApplication, and how to call inject().
What a Provider Is
A provider tells an injector how to produce a value for a token. The token is the lookup key. The recipe says how to build the value. When you write providedIn: 'root', Angular registers the provider for you. You can also register providers yourself in the providers array of bootstrapApplication, a route, or a component.
Provider Recipes
| Recipe | What the injector returns |
|---|---|
| `useClass` | A new instance of the class you name |
| `useValue` | The exact object you supply |
| `useFactory` | Whatever the factory function returns, created lazily on first request |
| `useExisting` | The instance already registered under another token (an alias) |
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 appProviders = [
{ provide: APP_CONFIG, useValue: { apiUrl: 'http://localhost:3000' } },
ConsoleLogger,
SilentLogger,
{
provide: Logger,
useFactory: () =>
inject(APP_CONFIG).apiUrl.includes('localhost')
? inject(ConsoleLogger)
: inject(SilentLogger)
},
{ provide: 'legacyLogger', useExisting: Logger }
];You pass appProviders to bootstrapApplication(AppComponent, { providers: appProviders }).
InjectionToken for Non-Class Values
Interfaces disappear at runtime, so AppConfig cannot be a token. InjectionToken<T> creates a unique runtime key that also carries the type T, so inject(APP_CONFIG) returns a typed AppConfig. String tokens such as 'legacyLogger' work, but they can collide and they are not typed. Use InjectionToken instead.
The Injector Hierarchy
Angular has two injector trees. Element injectors come from the providers arrays of components and directives. Environment injectors come from the application, from lazy routes, and from providedIn: 'root'. When a consumer asks for a token, Angular first walks up the element injectors, starting at the consumer and moving through each parent component. If none of them provides the token, it searches the environment injectors. If the token is still missing, NullInjector throws NullInjectorError.
The first injector that has the token wins. A provider placed closer to the consumer therefore shadows a root-level provider.
Exercise
CartService uses providedIn: 'root', and ShopComponent also lists CartService in its providers. Which instance does a child of ShopComponent receive, and which instance does a component outside ShopComponent receive?
Show answer
The child receives ShopComponent's own instance, because element injectors are checked before environment injectors. The component outside ShopComponent receives the root singleton.
Exercise
You register { provide: Logger, useClass: ConsoleLogger } and also list ConsoleLogger as a provider. Does inject(Logger) return the same object as inject(ConsoleLogger)?
Show answer
No. useClass builds a separate instance. Use { provide: Logger, useExisting: ConsoleLogger } to share one instance.