Sub topic 7
Injecting Configuration and Values with InjectionToken
This chapter assumes you know how to create a service with @Injectable, inject it with inject(), and register providers with useValue and useFactory from the previous chapters. You should also be comfortable with TypeScript interfaces and generics.
Why classes are not enough
Angular finds a dependency by looking up a key, called a token, in an injector. When you inject a class such as CartService, the class itself is the token. That works because a class exists at runtime as a JavaScript value.
Many dependencies are not classes. Examples include an API URL, a feature flag, a page size, or a configuration object described by an interface. TypeScript erases interfaces when it compiles, so nothing is left at runtime for Angular to use as a key. This code does not compile:
export interface AppConfig {
apiUrl: string;
}
// Error: 'AppConfig' only refers to a type, but is being used as a value here.
// providers: [{ provide: AppConfig, useValue: { apiUrl: '/api' } }]An InjectionToken fixes this. It is a small runtime object that stands in for the type, and its generic parameter tells TypeScript what value it carries.
Defining and providing a token
Put the interface and the token together in one file so every consumer imports the same object.
// app.config.ts
import { InjectionToken } from '@angular/core';
export interface AppConfig {
apiUrl: string;
retries: number;
}
export const APP_CONFIG = new InjectionToken<AppConfig>('APP_CONFIG');The string 'APP_CONFIG' is only a description. Angular shows it in error messages. Angular does not use it to look anything up.
Register a value for the token when the app starts:
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { APP_CONFIG } from './app/app.config';
bootstrapApplication(AppComponent, {
providers: [
{ provide: APP_CONFIG, useValue: { apiUrl: 'https://api.example.com', retries: 3 } }
]
});Injecting the value
You inject a token the same way you inject a class. The return type comes from the token's generic parameter, so config is typed as AppConfig without a cast.
// api-client.service.ts
import { Injectable, inject } from '@angular/core';
import { APP_CONFIG } from './app.config';
@Injectable({ providedIn: 'root' })
export class ApiClient {
private readonly config = inject(APP_CONFIG);
url(path: string): string {
return `${this.config.apiUrl}/${path}`;
}
}With constructor injection, a token needs the @Inject decorator because the parameter's type cannot act as the key:
// constructor(@Inject(APP_CONFIG) private readonly config: AppConfig) {}Tokens with a built-in default
A token can supply its own factory. When nobody provides the token, Angular calls the factory in the root injector. Like a providedIn: 'root' service, this kind of token is tree-shakable.
import { InjectionToken } from '@angular/core';
export const PAGE_SIZE = new InjectionToken<number>('PAGE_SIZE', {
providedIn: 'root',
factory: () => 20
});inject(PAGE_SIZE) returns 20 unless some provider overrides it, for example with { provide: PAGE_SIZE, useValue: 50 }. You can call inject() inside the factory to build the default from other dependencies.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `NullInjectorError: No provider for InjectionToken APP_CONFIG` | The token was never provided and has no factory | Add a provider or give the token a `factory` |
| Value is missing even though you provided it | Two separate `new InjectionToken(...)` calls with the same description | Export one token and import it everywhere |
| Compile error "only refers to a type" | An interface was used as a token | Create an `InjectionToken<YourInterface>` |
| Using a plain string like `'apiUrl'` as the token | Strings work, but they collide easily and lose type safety | Use an `InjectionToken` instead |
Exercise
You define export const FEATURE_FLAGS = new InjectionToken<Record<string, boolean>>('FEATURE_FLAGS'); but never provide it. A component calls inject(FEATURE_FLAGS). What happens, and how can you make it return {} by default without adding a provider at bootstrap?
Show answer
Angular throws a NullInjectorError because nothing provides the token. Pass options to the token: new InjectionToken<Record<string, boolean>>('FEATURE_FLAGS', { providedIn: 'root', factory: () => ({}) }). Angular then creates {} in the root injector whenever no other provider overrides the token.