Sub topic 2
Providers and injection tokens
This chapter assumes you can write a TypeScript class with a decorator, build a standalone component, and call a service from it. It covers the two ideas under every Angular dependency: the token that names a dependency and the provider that says how to build it. The chapters that follow use both to explain where providers can live.
A provider is a recipe attached to a token
An injector is an object that holds a map. The key is a token. The value is a provider, which is a recipe for producing the dependency. When code asks for a token, the injector finds the provider, runs the recipe once, caches the result, and returns the cached value on later requests.
A token is the lookup key. Three kinds are common:
- A class, such as
CounterService. The class object exists at runtime, so it works as a key. - An abstract class, such as
Panel. It works as a key and also describes the shape of the dependency. - An
InjectionToken, an object you create to name values that are not classes, such as strings, configuration objects or functions.
The provider forms
A provider is either a bare class or an object with a provide property. The provide property holds the token. A second property chooses the recipe.
| Form | Recipe |
|---|---|
| `SomeClass` | Shorthand for `{ provide: SomeClass, useClass: SomeClass }` |
| `{ provide: T, useClass: C }` | Create `C` with `new`, resolving its dependencies |
| `{ provide: T, useValue: v }` | Return `v` as is. No instantiation takes place |
| `{ provide: T, useFactory: fn }` | Call `fn` and use its return value |
| `{ provide: T, useExisting: Other }` | Return whatever the injector resolves for `Other` |
Class providers
The shorthand covers most services. Use the long form with useClass when the token and the implementation differ. The token below is an abstract class, so consumers depend on the contract and not on a concrete type.
import { Injectable, inject } from '@angular/core';
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 loggerProvider = {
provide: Logger,
useClass: ConsoleLogger,
};
export class ReportService {
private readonly logger = inject(Logger);
run(): void {
this.logger.log('report started');
}
}Registering { provide: Logger, useClass: SilentLogger } instead changes the behavior of every consumer without editing any of them. This is the main reason to separate the token from the implementation.
Value providers
useValue hands out an object you already have. Angular does not construct it or look at its type. It is the right choice for configuration, constants and test doubles.
Factory providers
useFactory is for values that need logic to build. Inside the factory function you can call inject() to request other dependencies. This works because Angular runs the factory in an injection context.
import { InjectionToken, inject } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { HttpClient, provideHttpClient } from '@angular/common/http';
import { AppComponent } from './app/app.component';
export const API_URL = new InjectionToken<string>('API_URL');
export class ApiClient {
constructor(
readonly baseUrl: string,
readonly http: HttpClient,
) {}
}
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(),
{ provide: API_URL, useValue: 'https://example.com/api' },
{
provide: ApiClient,
useFactory: () => new ApiClient(inject(API_URL), inject(HttpClient)),
},
],
});Older code lists the factory's dependencies in a deps array and takes them as arguments. Both styles work. The inject() style has fewer moving parts, because the dependency list cannot drift out of sync with the arguments.
Alias providers
useExisting makes one token an alias of another. It differs from useClass, which creates a second instance. With useExisting, both tokens return the same instance.
import { Injectable } from '@angular/core';
export abstract class Storage {
abstract save(key: string, value: string): void;
}
@Injectable({ providedIn: 'root' })
export class LocalStorageService extends Storage {
save(key: string, value: string): void {
localStorage.setItem(key, value);
}
}
export const storageAlias = { provide: Storage, useExisting: LocalStorageService };With the alias registered, inject(Storage) and inject(LocalStorageService) return one object, so state is shared. With useClass: LocalStorageService you would get two objects. The last chapter of this tutorial uses the alias form to let a child inject its parent component.
Creating an InjectionToken
An InjectionToken takes a description and an optional options object. The generic type is the type of the value that inject() returns for it.
import { InjectionToken } from '@angular/core';
export const API_URL = new InjectionToken<string>('API_URL', {
providedIn: 'root',
factory: () => '/api',
});The description string appears in error messages such as NullInjectorError: No provider for InjectionToken API_URL!. It does not identify the token. Two tokens with the same description are still different keys, because identity comes from the object itself.
The providedIn: 'root' and factory options make the token provide its own default. Nothing needs to register it. If no code registers API_URL, the root injector falls back to the factory and returns /api. Because the default lives with the token, a bundler can remove the token and its factory when no code uses them. This property is called being tree-shakable.
A token with no options, like new InjectionToken<string>('API_URL'), has no default. Injecting it without a provider throws.
Overriding a default
A provider registered in an injector beats the token's own default. This bootstrapApplication call replaces /api with a full URL for the whole application:
import { InjectionToken } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
export const API_URL = new InjectionToken<string>('API_URL', {
providedIn: 'root',
factory: () => '/api',
});
bootstrapApplication(AppComponent, {
providers: [{ provide: API_URL, useValue: 'https://example.com/api' }],
});If the same token is registered twice in one providers array, the later entry wins. The earlier one is silently ignored, which is a common source of confusion when providers come from several helper functions.
Several values under one token with multi
Setting multi: true changes what a token holds. Each registration adds to a list, and inject() returns the whole array. Angular itself uses this for HTTP interceptors and route guards. You can use it for plugin-style extension points.
import { InjectionToken, inject } from '@angular/core';
export interface Validator {
validate(value: string): string | null;
}
export const VALIDATORS = new InjectionToken<readonly Validator[]>('VALIDATORS');
export const required: Validator = {
validate: v => (v ? null : 'Required'),
};
export const maxLength: Validator = {
validate: v => (v.length <= 10 ? null : 'Too long'),
};
export const validationProviders = [
{ provide: VALIDATORS, useValue: required, multi: true },
{ provide: VALIDATORS, useValue: maxLength, multi: true },
];
export function validateAll(value: string): string[] {
return inject(VALIDATORS)
.map(v => v.validate(value))
.filter((e): e is string => e !== null);
}Note that validateAll calls inject() itself, so you can only call it from an injection context, such as a constructor, a field initializer or a factory. The token's type is an array, because that is what the consumer receives. Every provider for a multi token must set multi: true. Mixing a multi and a non-multi provider for the same token in one injector throws an error.
Grouping providers into functions
Library authors expose providers through functions instead of asking you to copy provider objects. provideHttpClient() is an example. Your own code can do the same. Return a plain array and callers can spread it into any providers list.
import { Provider } from '@angular/core';
import { API_URL } from './tokens';
export function provideApi(url: string): Provider[] {
return [{ provide: API_URL, useValue: url }];
}For providers that are only valid in an environment injector, Angular offers makeEnvironmentProviders. The next chapters explain what that means. For now, treat Provider[] as enough.
Where the provider is declared still matters
A provider only takes effect in the injector that holds it. The same { provide: Logger, useClass: ConsoleLogger } object can appear in bootstrap options, in a route, or in a component's providers. The recipe is identical, but the cache of values is separate in each place, so the number of instances changes. The following chapters build on this.
Exercise
A component needs to be told its API address, which is a plain string that differs between development and production. A teammate proposes export interface ApiUrl { value: string } and inject(ApiUrl). Why does that fail, and what would you write instead so that a missing registration still yields /api?
Show answer
An interface is erased at compile time, so no runtime key exists and inject(ApiUrl) cannot work. Create a token: export const API_URL = new InjectionToken<string>('API_URL', { providedIn: 'root', factory: () => '/api' });. Components call inject(API_URL). Production overrides it with { provide: API_URL, useValue: 'https://example.com/api' } in the providers of bootstrapApplication. Without an override, the factory supplies /api.
Exercise
{ provide: Storage, useClass: LocalStorageService } and { provide: Storage, useExisting: LocalStorageService } are both registered in turn. Which one lets inject(Storage) and inject(LocalStorageService) return the same object, and why?
Show answer
useExisting. It resolves LocalStorageService through the injector and returns that cached instance under the second token. useClass runs new LocalStorageService() for the Storage token, which gives it its own instance, separate from the one cached under LocalStorageService.