Sub topic 2
Providers and injection tokens
This chapter assumes you know TypeScript classes and decorators, standalone components, and how to write a basic Angular service. Here you learn what a provider is and what a token is. Later chapters cover where providers can be declared.
A provider links a token to a value
Angular's injector keeps a lookup table. Each entry has a token (the key) and a provider (a recipe for making the value). When code asks for a token, the injector runs the recipe. It then caches the result, so each injector creates a given dependency once.
The simplest token is a class. A class works as a token because it exists at runtime. TypeScript interfaces are erased at compile time, so they cannot be tokens.
Provider forms
Every provider is an object with a provide key (the token) and one recipe key.
| Recipe key | What the injector does |
|---|---|
| `useClass` | Creates an instance of the given class |
| `useValue` | Returns the given value as is |
| `useFactory` | Calls the function and returns its result |
| `useExisting` | Returns whatever another token resolves to |
Writing a bare class in a providers array, such as providers: [CounterService], is shorthand for { provide: CounterService, useClass: CounterService }.
import { inject, InjectionToken } from '@angular/core';
export const GREETING = new InjectionToken<string>('GREETING');
export class Logger {
log(message: string): void {
console.log(message);
}
}
export class QuietLogger extends Logger {
override log(): void {}
}
export const providers = [
{ provide: Logger, useClass: QuietLogger },
{ provide: GREETING, useFactory: () => `Hello from ${inject(Logger).constructor.name}` },
];Inside a useFactory function you can call inject() to get other dependencies. Angular runs the factory in an injection context.
Injection tokens for non-class values
Strings, numbers, and configuration objects need an InjectionToken. The string you pass is only a debugging label. Token identity is the object itself, so two tokens with the same label are different keys.
An InjectionToken can carry its own default. With providedIn: 'root' and a factory, the token works without any registration. Anything you provide explicitly replaces that default:
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' }],
});Without the factory, asking for an unprovided token throws NullInjectorError.
Aliases with useExisting
useExisting makes a second token point to the same instance as the first. useClass would create a second instance. Use useExisting when you want one object reachable under two names:
import { Injectable } from '@angular/core';
export abstract class Storage2 {
abstract get(key: string): string | null;
}
@Injectable({ providedIn: 'root' })
export class LocalStorageService extends Storage2 {
get(key: string): string | null {
return localStorage.getItem(key);
}
}
export const storageProvider = { provide: Storage2, useExisting: LocalStorageService };Exercise
You write { provide: API_URL, useClass: 'https://example.com/api' }. Which recipe key is correct, and why must API_URL be an InjectionToken rather than an interface?
Show answer
Use useValue, because the recipe is a plain string and not a class. API_URL must be an InjectionToken because interfaces are erased at compile time, so no runtime object exists for the injector to use as a key.