Not everything you inject is a class. This part covers InjectionToken, the four kinds of provider, @Service with a factory, the injector tree, and the optional, self, skipSelf and host options of inject().
In Part 13 we injected classes. A class marked @Service() is created once for the whole app, and any component gets it with inject(). A component can also list a class in its own providers, and then it and its children get their own copy. If nothing provides a class, Angular stops with NG0201.
That covers most of an app. But some things you want to inject aren’t classes: an API address, a set of feature flags, a different logger for tests. And sometimes a component needs to say where to look, like a nested menu looking for its parent menu. This part covers InjectionToken, the four kinds of provider, @Service() with a factory, the injector tree, and the options that change how inject() searches. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.
Try this first
Paste this into src/app/app.ts. It has a GREETING that isn’t a class, and a card that shows it. One card sits straight in App. The other sits inside a Panel, which has a providers list of its own.
// src/app/app.ts
import { Component, InjectionToken, inject } from '@angular/core';
export const GREETING = new InjectionToken<string>('GREETING', { factory: () => 'Hello' });
@Component({ selector: 'app-card', template: `<p>{{ greeting }} from a card</p>` })
export class Card {
protected readonly greeting = inject(GREETING);
}
@Component({
selector: 'app-panel',
imports: [Card],
providers: [{ provide: GREETING, useValue: 'Hi' }],
template: `<app-card />`,
})
export class Panel {}
@Component({
selector: 'app-root',
imports: [Card, Panel],
template: `
<app-card />
<app-panel />
`,
})
export class App {}
Before you read on, guess. The two cards are the same component, with the same inject(GREETING). What does each line say?
The page shows:
Hello from a card
Hi from a card
The first card got the default, 'Hello', from the token’s factory. The second card asked the same question but got Panel‘s answer, because Panel sat between it and the default. By the end of this part you’ll know each piece of that.
Why a class isn’t enough
When you write inject(Cart), the class Cart does two jobs. It’s the key Angular looks up, and it’s the recipe for making the value: call new Cart(). Angular calls the key a token.
A string has no class to use as a key. inject(String) can’t tell the API address from any other string. A TypeScript interface can’t be a key either. Interfaces only exist while TypeScript checks your code. They’re gone when the code runs, so there’s nothing for Angular to look up.
InjectionToken makes a key for a value that isn’t a class:
// src/app/config.ts
import { InjectionToken } from '@angular/core';
export interface AppConfig {
apiUrl: string;
appName: string;
}
export const APP_CONFIG = new InjectionToken<AppConfig>('APP_CONFIG');
Three things to notice:
new InjectionToken<AppConfig>(...)uses a generic, as in Part 3. It tells TypeScript that whatever Angular hands back for this key is anAppConfig. Soinject(APP_CONFIG).apiUrlis astring, and a typo likeapiURLwon’t build.- The
'APP_CONFIG'text is only a description. Angular prints it in error messages. Two tokens made with the same description are still two different keys. The key is the object, so make it once, export it, and import it everywhere. - By convention, token names are in capitals, like other constants.
The token is only a key. Something still has to say what value goes with it. That’s a provider. The app-wide place for providers is src/app/app.config.ts, the file ng new made. Here it is with one more line:
// src/app/app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { APP_CONFIG } from './config';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
{ provide: APP_CONFIG, useValue: { apiUrl: '/api', appName: 'Notes' } },
],
};
{ provide: APP_CONFIG, useValue: {...} } reads as “when someone asks for APP_CONFIG, give them this object”. The other two lines are the ones ng new wrote. provideRouter sets up routing, which Part 16 covers; for now, leave it there.
Now any component can ask for it:
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { APP_CONFIG } from './config';
@Component({
selector: 'app-root',
template: `<p>{{ config.appName }} talks to {{ config.apiUrl }}</p>`,
})
export class App {
protected readonly config = inject(APP_CONFIG);
}
The page shows:
Notes talks to /api
App doesn’t know where the value came from. A test could provide a different object, and App wouldn’t change.
A token with no provider
What if you make a token and forget the provider? Here a price component asks for an API_URL that nobody provides. It sits behind a Show price button, so the page loads first:
// src/app/app.ts
import { Component, InjectionToken, inject, signal } from '@angular/core';
export const API_URL = new InjectionToken<string>('API_URL');
@Component({ selector: 'app-price', template: `<p>Prices from {{ url }}</p>` })
export class Price {
protected readonly url = inject(API_URL);
}
@Component({
selector: 'app-root',
imports: [Price],
template: `
<button (click)="show.set(true)">Show price</button>
@if (show()) {
<app-price />
}
`,
})
export class App {
protected readonly show = signal(false);
}
It builds. Click Show price, and nothing appears. The console has:
ERROR ɵNotFound: NG0201: No provider found for `InjectionToken API_URL`. Source: Environment Injector. Find more at https://v22.angular.dev/errors/NG0201
This is the NG0201 from Part 13, with a token instead of a class. `InjectionToken API_URL` is the description you gave the token, which is why it’s worth writing a clear one. Source: Environment Injector names the app’s root environment injector, the app-wide one. The search reached it without finding a provider, and nothing above it had one either. We’ll see that path in a figure below. The build can’t catch this, because providers are only collected when the app runs.
You can fix it with a provider in app.config.ts, as before. Or you can give the token a default.
A default value: a token with a factory
The second argument to InjectionToken can carry a factory, a function that makes the value when nobody provided one:
// src/app/features.ts
import { InjectionToken } from '@angular/core';
export interface Features {
darkMode: boolean;
newCheckout: boolean;
}
export const FEATURES = new InjectionToken<Features>('FEATURES', {
factory: () => ({ darkMode: false, newCheckout: false }),
});
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { FEATURES } from './features';
@Component({
selector: 'app-root',
template: `<p>New checkout: {{ features.newCheckout ? 'on' : 'off' }}</p>`,
})
export class App {
protected readonly features = inject(FEATURES);
}
With the stock app.config.ts, the page shows:
New checkout: off
That’s how GREETING worked in Try this first. The factory acts as if it were a provider in the app-wide injector, so you don’t write a line in app.config.ts for it. Angular runs it the first time someone asks, and keeps the result, like a @Service(). If no code uses the token at all, the build tool can leave it and its factory out of the bundle. That’s called tree-shakable: unused code falls out, like dead leaves from a shaken tree.
A provider still beats the default. Add one to app.config.ts:
// src/app/app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { FEATURES } from './features';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
{ provide: FEATURES, useValue: { darkMode: false, newCheckout: true } },
],
};
Now the page shows:
New checkout: on
Give a token a factory when there’s a sensible default. Leave it out when there isn’t one, like a server address. Then a missing provider fails loudly with NG0201 instead of quietly using a made-up value.
Four kinds of provider
useValue is one way to answer “what goes with this token?”. There are four. Each is an object with provide (the token) and one of these:
| Provider | What Angular hands out |
|---|---|
{ provide: T, useValue: v } |
the value v, as it is |
{ provide: T, useClass: C } |
a new C, made by Angular |
{ provide: T, useExisting: U } |
whatever token U already gives: an alias |
{ provide: T, useFactory: f } |
whatever the function f returns |
Writing a class on its own, providers: [Cart], is short for { provide: Cart, useClass: Cart }.
Here are useFactory and useExisting at work. They’re in App‘s providers to keep the example in one file; the same objects work in app.config.ts.
// src/app/app.ts
import { Component, InjectionToken, Service, inject } from '@angular/core';
export const APP_NAME = new InjectionToken<string>('APP_NAME', { factory: () => 'Notes' });
export const TITLE = new InjectionToken<string>('TITLE');
export const INITIAL = new InjectionToken<string>('INITIAL');
@Service()
export class Logger {
log(message: string) {
console.log(`[log] ${message}`);
}
}
export abstract class OldLogger {
abstract log(message: string): void;
}
@Component({
selector: 'app-root',
providers: [
{ provide: TITLE, useFactory: () => `${inject(APP_NAME)}, version 2` },
{ provide: INITIAL, useFactory: (name: string) => name[0], deps: [APP_NAME] },
{ provide: OldLogger, useExisting: Logger },
],
template: `
<p>{{ title }} ({{ initial }})</p>
<p>Same logger: {{ sameLogger }}</p>
`,
})
export class App {
protected readonly title = inject(TITLE);
protected readonly initial = inject(INITIAL);
protected readonly sameLogger = inject(OldLogger) === inject(Logger);
constructor() {
inject(OldLogger).log('hello from old code');
}
}
The page shows:
Notes, version 2 (N)
Same logger: true
and the console has:
[log] hello from old code
What each one did:
TITLEuses a factory that callsinject()itself. A factory runs in an injection context, the same place a field initializer runs, soinject()works there. This is the form to use in new code.INITIALuses the olderdepsform. Angular looks up each token indepsand passes the values to the factory as arguments, in order.name[0]is the first letter. You’ll seedepsin existing code;inject()inside the factory does the same job and is easier to read.OldLoggeris an alias.useExisting: Loggermeans “give out theLoggeryou already have”. There’s still one logger, which is whySame loggeristrue. Aliases help when old code asks for an old name and you’ve moved to a new class. WithuseClass: Loggerinstead, Angular would make a secondLoggerjust for that token, and the answer would befalse. Exercise 3 checks that.
OldLogger is an abstract class: a class you can’t create with new, only extend. It’s still a real class when the code runs, so it can be a token, unlike an interface. That makes it handy as a key that also describes the shape, which the next section uses.
@Service with a factory
@Service() from Part 13 has a factory option too. It lets an abstract class name a default implementation:
// src/app/logger.ts
import { Service } from '@angular/core';
@Service({ factory: () => new ConsoleLogger() })
export abstract class Logger {
abstract log(message: string): void;
}
export class ConsoleLogger extends Logger {
log(message: string) {
console.log(`[console] ${message}`);
}
}
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { Logger } from './logger';
@Component({
selector: 'app-root',
template: `<button (click)="save()">Save</button>`,
})
export class App {
private readonly logger = inject(Logger);
protected save() {
this.logger.log('saved');
}
}
Click Save. The console shows:
[console] saved
Components ask for Logger, the abstract class. They never name ConsoleLogger. The factory says what to make when nothing else is provided, and Angular calls it once and shares the result, like any @Service(). It’s the class version of a token with a factory: a default that a provider can replace. The first worked example below replaces it.
In older code you’ll see the same idea as @Injectable({ providedIn: 'root', useFactory: () => new ConsoleLogger() }).
Many values for one token: multi providers
Usually a second provider for a token replaces the first. With multi: true on each, Angular collects them all into an array:
// src/app/app.ts
import { Component, InjectionToken, inject } from '@angular/core';
export const NAV_LINKS = new InjectionToken<string[]>('NAV_LINKS');
@Component({
selector: 'app-root',
providers: [
{ provide: NAV_LINKS, useValue: 'Home', multi: true },
{ provide: NAV_LINKS, useValue: 'Notes', multi: true },
{ provide: NAV_LINKS, useValue: 'Settings', multi: true },
],
template: `<p>{{ links.join(' | ') }}</p>`,
})
export class App {
protected readonly links = inject(NAV_LINKS);
}
The page shows:
Home | Notes | Settings
Notice the token’s type is string[], while each provider gives one string. Multi providers let separate parts of an app each add an entry. Angular uses them inside: provideAppInitializer(), later in this part, adds to one. You’ll rarely write one yourself.
The injector tree
So far “Angular looks it up” has been vague. Here’s what really happens. Angular keeps many injectors, each a box of providers, joined into a tree. There are two kinds.
Environment injectors hold app-wide things:
- the root environment injector holds everything in
app.config.ts, every@Service(), and every token factory; - above it, the platform injector holds a few things Angular shares between every app on the page;
- above that is a last “null” injector, whose only job is to throw NG0201.
Routing (Part 16) can add one more: a route can have its own environment injector, between the root and the components on that route.
Element injectors belong to the components and directives in your templates. A component’s providers go in its element injector. These form a tree that follows your templates: App, then the components in App‘s template, then the ones in theirs.
When a component calls inject(X), Angular searches in this order:
- the component’s own element injector;
- its parent’s, then the parent’s parent, up to
App; - the root environment injector, then platform, then null, which throws.
The first one that has X wins. That’s why the second card in Try this first said “Hi”: Panel‘s element injector came before the root.
inject() searches the element injectors first, from the component that asks up to App, then the environment injectors. The first match wins.
The classic mistake: one service, two copies
That search order explains a bug almost everyone hits once. A Cart is a @Service(), so the root already has one. But two components also list it in their own providers:
// src/app/cart.ts
import { Service, signal } from '@angular/core';
@Service()
export class Cart {
readonly count = signal(0);
}
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { Cart } from './cart';
@Component({
selector: 'app-badge',
providers: [Cart],
template: `<p>Cart: {{ cart.count() }}</p>`,
})
export class Badge {
protected readonly cart = inject(Cart);
}
@Component({
selector: 'app-add',
providers: [Cart],
template: `<button (click)="cart.count.update((n) => n + 1)">Add</button>`,
})
export class AddButton {
protected readonly cart = inject(Cart);
}
@Component({
selector: 'app-root',
imports: [Badge, AddButton],
template: `
<app-badge />
<app-add />
`,
})
export class App {}
Click Add twice. The page shows:
Cart: 0
Add
The badge never moves. Each component’s search stopped at its own element injector, which made its own Cart. So there are three carts: the button’s, the badge’s, and the unused one in the root. The button counts up in a cart nobody shows.
The fix is to delete both providers: [Cart] lines. Then both searches go past the components and end at the root’s one Cart:
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { Cart } from './cart';
@Component({
selector: 'app-badge',
template: `<p>Cart: {{ cart.count() }}</p>`,
})
export class Badge {
protected readonly cart = inject(Cart);
}
@Component({
selector: 'app-add',
template: `<button (click)="cart.count.update((n) => n + 1)">Add</button>`,
})
export class AddButton {
protected readonly cart = inject(Cart);
}
@Component({
selector: 'app-root',
imports: [Badge, AddButton],
template: `
<app-badge />
<app-add />
`,
})
export class App {}
Click Add twice. The page shows:
Cart: 2
Add
A component’s providers means “my own copy, for me and my children”. That’s right for a form that keeps its own draft. It’s wrong for anything the whole app should share.
You may also meet viewProviders in a component. It works like providers, except content passed in with ng-content (Part 9) can’t see it. It’s rare in app code.
Changing where inject() looks
inject() takes a second argument with four options. Each changes the search above.
optional: true returns null instead of throwing NG0201. Use it for something the app may or may not have. Here Analytics uses autoProvided: false from Part 13, so nothing provides it unless you add it to providers:
// src/app/app.ts
import { Component, Service, inject } from '@angular/core';
@Service({ autoProvided: false })
export class Analytics {
track(event: string) {
console.log(`tracked ${event}`);
}
}
@Component({
selector: 'app-root',
template: `<p>Analytics: {{ analytics ? 'on' : 'off' }}</p>`,
})
export class App {
protected readonly analytics = inject(Analytics, { optional: true });
constructor() {
this.analytics?.track('page view');
}
}
The page shows:
Analytics: off
and nothing is logged. TypeScript knows the result might be null: its type is Analytics | null. So it makes you write this.analytics?.track(...), where ?. means “only call it if it isn’t null”.
self: true searches only the component’s own element injector. If it isn’t there, it fails, even when the root has one. Use it when a component must have its own copy and getting a shared one by accident would be a bug.
skipSelf: true starts the search one step up, at the parent. A component uses it to find another of its own kind above it, as the menu in the worked example below does.
host: true stops the search at the host component: the component whose template the asker is written in. It doesn’t go on to that component’s parents or to the root. In Angular 22.3 we found it sees the host’s viewProviders but not its providers. It’s mostly used by directives, and you’ll rarely need it.
You can combine them. { skipSelf: true, optional: true } means “look above me, and give me null if there’s nothing”.
Running code before the app starts
Sometimes the app needs something done before the first component appears, like loading settings. provideAppInitializer() in app.config.ts takes a function. If the function returns a promise, Angular waits for it before it creates App:
// src/app/app.config.ts
import {
ApplicationConfig,
provideAppInitializer,
provideBrowserGlobalErrorListeners,
} from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideAppInitializer(() => {
console.log('initializer started');
return new Promise<void>((resolve) => setTimeout(resolve, 200));
}),
],
};
// src/app/app.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `<p>Ready</p>`,
})
export class App {
constructor() {
console.log('App created');
}
}
The console shows:
initializer started
App created
The function runs in an injection context, so it can call inject(). Keep initializers short: the user sees a blank page until they finish.
Worked example: a config for each environment
Real apps talk to one server while you develop and another when they’re live. Angular has a function for telling them apart: isDevMode() returns true under ng serve and false in a production build from ng build. A useFactory provider can pick the config:
// src/app/config.ts
import { InjectionToken } from '@angular/core';
export interface AppConfig {
apiUrl: string;
appName: string;
}
export const APP_CONFIG = new InjectionToken<AppConfig>('APP_CONFIG');
export const devConfig: AppConfig = { apiUrl: 'http://localhost:3000/api', appName: 'Notes (dev)' };
export const prodConfig: AppConfig = { apiUrl: 'https://notes.example.com/api', appName: 'Notes' };
// src/app/app.config.ts
import { ApplicationConfig, isDevMode, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { APP_CONFIG, devConfig, prodConfig } from './config';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
{ provide: APP_CONFIG, useFactory: () => (isDevMode() ? devConfig : prodConfig) },
],
};
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { APP_CONFIG } from './config';
@Component({
selector: 'app-root',
template: `<p>{{ config.appName }} talks to {{ config.apiUrl }}</p>`,
})
export class App {
protected readonly config = inject(APP_CONFIG);
}
Under ng serve, the page shows:
Notes (dev) talks to http://localhost:3000/api
After ng build, the same page says Notes talks to https://notes.example.com/api.
The point is where the choice lives. App only asks for APP_CONFIG. The one place that knows about environments is app.config.ts.
Angular can also generate environment.ts files that the build swaps (ng generate environments). A token on top of them still helps: components inject the values instead of importing a file, so tests can replace them.
Worked example: swapping a logger with useClass
The Logger from earlier has a default, ConsoleLogger. Say we want a logger that keeps its lines in memory and shows them on the page, for a demo or a test. Components shouldn’t change at all.
// src/app/logger.ts
import { Service, signal } from '@angular/core';
@Service({ factory: () => new ConsoleLogger() })
export abstract class Logger {
abstract log(message: string): void;
}
export class ConsoleLogger extends Logger {
log(message: string) {
console.log(`[console] ${message}`);
}
}
export class MemoryLogger extends Logger {
readonly lines = signal<string[]>([]);
log(message: string) {
this.lines.update((lines) => [...lines, message]);
}
}
// src/app/app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { Logger, MemoryLogger } from './logger';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
{ provide: Logger, useClass: MemoryLogger },
],
};
// src/app/log-view.ts
import { Component, inject } from '@angular/core';
import { Logger, MemoryLogger } from './logger';
@Component({
selector: 'app-log-view',
template: `
@if (memory) {
<ul>
@for (line of memory.lines(); track $index) {
<li>{{ line }}</li>
}
</ul>
} @else {
<p>Logging to the console</p>
}
`,
})
export class LogView {
private readonly logger = inject(Logger);
protected readonly memory = this.logger instanceof MemoryLogger ? this.logger : null;
}
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { LogView } from './log-view';
import { Logger } from './logger';
@Component({
selector: 'app-root',
imports: [LogView],
template: `
<button (click)="save()">Save</button>
<app-log-view />
`,
})
export class App {
private readonly logger = inject(Logger);
private saves = 0;
protected save() {
this.saves++;
this.logger.log(`saved ${this.saves}`);
}
}
instanceof is plain JavaScript: it checks whether an object was made from a class. The log view uses it to show the lines when it has a MemoryLogger.
Click Save twice. We expect the two lines on the page. Instead, the page shows:
Save
Logging to the console
The console has the two lines we didn’t want, and a warning before them:
[console] saved 1
[console] saved 2
DEPRECATED: DI is instantiating a token "MemoryLogger" that inherits its @Injectable decorator but does not provide one itself.
This will become an error in a future version of Angular. Please add @Injectable() to the "MemoryLogger" class.
Read the warning slowly. Angular was asked to make a MemoryLogger. MemoryLogger has no decorator of its own, so Angular used the one it inherits from Logger. That decorator carries Logger’s factory, and the factory makes a ConsoleLogger. So useClass: MemoryLogger quietly gave us a console logger. The message says @Injectable because @Service() is built on the same machinery.
The fix is the one the warning asks for, in its modern form. Give MemoryLogger a decorator of its own. autoProvided: false says it’s only used where we provide it:
// src/app/logger.ts
import { Service, signal } from '@angular/core';
@Service({ factory: () => new ConsoleLogger() })
export abstract class Logger {
abstract log(message: string): void;
}
export class ConsoleLogger extends Logger {
log(message: string) {
console.log(`[console] ${message}`);
}
}
@Service({ autoProvided: false })
export class MemoryLogger extends Logger {
readonly lines = signal<string[]>([]);
log(message: string) {
this.lines.update((lines) => [...lines, message]);
}
}
ConsoleLogger doesn’t need one, because its factory calls new itself; Angular never makes it. Click Save twice. The page shows:
Save
saved 1
saved 2
Nothing went to the console. { provide: Logger, useClass: MemoryLogger } in the root replaced the factory default, and Angular made one MemoryLogger that App and LogView share.
Now take that line out of app.config.ts, and keep every other file:
// src/app/app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideBrowserGlobalErrorListeners(), provideRouter(routes)],
};
Click Save once. The page shows:
Save
Logging to the console
and the console has:
[console] saved 1
The factory default is back, and not one component changed.
useClass is the right tool here because Angular makes the object. With useValue: new MemoryLogger() you’d make it yourself, outside Angular, so it couldn’t call inject() in its fields.
Worked example: a nested menu and NG0200
A menu can hold other menus. Each menu wants to know its parent, to show a path like File > Recent. Components are in their element injector too, so a component can inject another component above it. A first try asks for Menu:
// src/app/menu.ts
import { Component, inject, input } from '@angular/core';
@Component({
selector: 'app-menu',
template: `
<p>{{ label() }}</p>
<ng-content />
`,
})
export class Menu {
readonly label = input.required<string>();
private readonly parent = inject(Menu, { optional: true });
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Menu } from './menu';
@Component({
selector: 'app-root',
imports: [Menu],
template: `
<button (click)="open.set(true)">Open menu</button>
@if (open()) {
<app-menu label="File">
<app-menu label="Recent" />
</app-menu>
}
`,
})
export class App {
protected readonly open = signal(false);
}
input.required is from Part 5, and <ng-content /> from Part 9: the inner menu is passed into the outer one. It builds. Click Open menu. Nothing appears, and the console shows:
ERROR RuntimeError: NG0200: Circular dependency detected for `_Menu`. Path: _Menu -> _Menu. Find more at https://v22.angular.dev/errors/NG0200
Read it piece by piece:
NG0200is Angular’s code for a circular dependency: making one thing needed itself, directly or through others.`_Menu`is ourMenuclass. The_comes from the build tool: when a class’s code refers to its own name, it compiles the class asvar Menu = class _Menu {...}, and the code Angular adds to every decorated class does that.MemoryLoggerkeeps its plain name because it has no Angular decorator of its own.Path: _Menu -> _Menuis the chain. Making aMenuasked for aMenu, and the first one Angular found was the one it was in the middle of making: itself. The search starts at the asker’s own element injector, and a component is in its own.optional: truedidn’t help. It turns “not found” intonull. This was found, just not finished.
When two services inject each other, the path is longer, like _Auth -> _Api -> _Auth. The fix there is usually a third service that both can use.
Here the fix is to start the search one step up, with skipSelf. optional stays, because the top menu has no parent:
// src/app/menu.ts
import { Component, inject, input } from '@angular/core';
@Component({
selector: 'app-menu',
template: `
<p>{{ path() }} (level {{ level }})</p>
<ng-content />
`,
})
export class Menu {
readonly label = input.required<string>();
private readonly parent = inject(Menu, { skipSelf: true, optional: true });
readonly level: number = this.parent ? this.parent.level + 1 : 0;
path(): string {
return this.parent ? `${this.parent.path()} > ${this.label()}` : this.label();
}
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Menu } from './menu';
@Component({
selector: 'app-root',
imports: [Menu],
template: `
<app-menu label="File">
<app-menu label="Recent">
<app-menu label="Old" />
</app-menu>
<app-menu label="Save" />
</app-menu>
`,
})
export class App {}
The page shows:
File (level 0)
File > Recent (level 1)
File > Recent > Old (level 2)
File > Save (level 1)
Each menu found the nearest Menu above it, not any menu. Old got Recent, and Save got File. The element injector tree followed App‘s template, where each inner <app-menu> sits inside an outer one.
level and path are public, not protected, because child menus read them. level is a plain field, worked out once, because a menu’s parent never changes.
In older code
Before inject(), services came in through the constructor. A token needed the @Inject() decorator, and the search options were decorators on the parameter:
constructor(
@Inject(APP_CONFIG) private config: AppConfig,
@Optional() @SkipSelf() private parent: Menu | null,
) {}
@Optional(), @Self(), @SkipSelf() and @Host() match the options of the same names. A @Service() was @Injectable({ providedIn: 'root' }). Code that ran before the app started was a multi provider of APP_INITIALIZER with useFactory; provideAppInitializer() replaced it. All of these still work, but new code uses inject() with options.
Best practices
- Use an
InjectionTokenfor any value that isn’t a class. Give it a type and a clear description, and export it from one file. It replaces importing a constants file straight into components, which tests can’t swap. - Give a token or an abstract service a
factorywhen there’s a good default. It needs no line inapp.config.tsand drops out of the bundle if unused. It replaces providing every default by hand. Leave the default out for values that must be set, so a missing one fails with NG0201. - Put app-wide providers in
app.config.ts, and use componentprovidersonly for a copy per component. It replaces listing shared services in a component and getting several copies. - Depend on an abstract class, and choose the implementation with
useClassin one place. Components stay the same when you swap a console logger for a memory logger or a fake. It replacesif (testing)checks inside services. - Prefer
inject()inside auseFactorytodeps. It reads in order and can take options. It replaces matching adepsarray to argument positions by hand.
Tips and traps
- Two tokens with the same description. Making
new InjectionToken('API_URL')in two files gives two keys. The provider fills one, and the component asks for the other, so you get NG0201 for a token you’re sure you provided. Make the token once and import it. - A service in a component’s
providersthat should be shared. Each component gets its own copy, so one part of the page changes a value another part never sees. No error appears. Remove theprovidersentry and let the root’s copy serve everyone. - Using an interface as a token.
inject(AppConfig)with an interface fails to build, because the interface doesn’t exist when the code runs. Use anInjectionToken<AppConfig>, or an abstract class. optional: trueto hide an NG0200. A circular dependency isn’t “not found”, sooptionaldoesn’t help. Find the loop inPath:and break it, withskipSelfor a third service.useClasswhere you meantuseExisting.useClassmakes a new instance for that token. If the old name and the new name should share state, useuseExisting.- A subclass with no decorator in
useClass. If the parent class has@Service({ factory }), the subclass inherits it, and Angular makes whatever the parent’s factory makes. It shows up as aDEPRECATED: DI is instantiating a token ... that inherits its @Injectable decoratorwarning and the wrong implementation. Give the subclass its own@Service({ autoProvided: false }). - Slow work in
provideAppInitializer. The page stays blank until every initializer’s promise finishes. Load only what the first screen truly needs there.
inject()asks the nearest element injector first and the root last, and the first provider it finds wins.
Exercises
Exercise 1. This page shows a theme name from a token when you click Show theme. Paste it and click. Nothing appears. What does the console say, and why? Fix it so the page shows Theme: light without touching app.config.ts.
// src/app/app.ts
import { Component, InjectionToken, inject, signal } from '@angular/core';
export const THEME = new InjectionToken<string>('THEME');
@Component({ selector: 'app-theme', template: `<p>Theme: {{ theme }}</p>` })
export class ThemeLabel {
protected readonly theme = inject(THEME);
}
@Component({
selector: 'app-root',
imports: [ThemeLabel],
template: `
<button (click)="show.set(true)">Show theme</button>
@if (show()) {
<app-theme />
}
`,
})
export class App {
protected readonly show = signal(false);
}
Exercise 2. Write a Toolbar component that wants an optional HelpService (a @Service({ autoProvided: false }) with a link field of '/help'). If it has one, it shows Help: /help. If not, it shows No help. Put two toolbars in App: one inside a Panel component that lists HelpService in its providers, and one straight in App.
Exercise 3. Without running it, what does the page show after you click Add once?
// src/app/app.ts
import { Component, Service, WritableSignal, inject, signal } from '@angular/core';
@Service()
export class Counter {
readonly count = signal(0);
}
export abstract class Score {
abstract readonly count: WritableSignal<number>;
}
export abstract class Points {
abstract readonly count: WritableSignal<number>;
}
@Component({
selector: 'app-root',
providers: [
{ provide: Score, useExisting: Counter },
{ provide: Points, useClass: Counter },
],
template: `
<button (click)="counter.count.update((n) => n + 1)">Add</button>
<p>Counter {{ counter.count() }}, Score {{ score.count() }}, Points {{ points.count() }}</p>
`,
})
export class App {
protected readonly counter = inject(Counter);
protected readonly score = inject(Score);
protected readonly points = inject(Points);
}
Answers
1. THEME has no provider and no factory, so inject(THEME) fails when the label is made. The console shows NG0201, No provider found for `InjectionToken THEME`. Give the token a default with a factory:
// src/app/app.ts
import { Component, InjectionToken, inject, signal } from '@angular/core';
export const THEME = new InjectionToken<string>('THEME', { factory: () => 'light' });
@Component({ selector: 'app-theme', template: `<p>Theme: {{ theme }}</p>` })
export class ThemeLabel {
protected readonly theme = inject(THEME);
}
@Component({
selector: 'app-root',
imports: [ThemeLabel],
template: `
<button (click)="show.set(true)">Show theme</button>
@if (show()) {
<app-theme />
}
`,
})
export class App {
protected readonly show = signal(false);
}
Click Show theme. The page shows:
Show theme
Theme: light
A provider in ThemeLabel‘s own providers, { provide: THEME, useValue: 'light' }, would work too.
2. inject(HelpService, { optional: true }) gives the service or null. The toolbar in the panel finds the panel’s copy on the way up. The other reaches the root, where autoProvided: false means there’s none.
// src/app/app.ts
import { Component, Service, inject } from '@angular/core';
@Service({ autoProvided: false })
export class HelpService {
readonly link = '/help';
}
@Component({
selector: 'app-toolbar',
template: `<p>{{ help ? 'Help: ' + help.link : 'No help' }}</p>`,
})
export class Toolbar {
protected readonly help = inject(HelpService, { optional: true });
}
@Component({
selector: 'app-panel',
imports: [Toolbar],
providers: [HelpService],
template: `<app-toolbar />`,
})
export class Panel {}
@Component({
selector: 'app-root',
imports: [Toolbar, Panel],
template: `
<app-panel />
<app-toolbar />
`,
})
export class App {}
The page shows:
Help: /help
No help
3. Counter 1, Score 1, Points 0. Score is an alias, so it’s the same Counter the button changes. Points uses useClass, so Angular made a second Counter for it, and nothing changes that one.
// src/app/app.ts
import { Component, Service, WritableSignal, inject, signal } from '@angular/core';
@Service()
export class Counter {
readonly count = signal(0);
}
export abstract class Score {
abstract readonly count: WritableSignal<number>;
}
export abstract class Points {
abstract readonly count: WritableSignal<number>;
}
@Component({
selector: 'app-root',
providers: [
{ provide: Score, useExisting: Counter },
{ provide: Points, useClass: Counter },
],
template: `
<button (click)="counter.count.update((n) => n + 1)">Add</button>
<p>Counter {{ counter.count() }}, Score {{ score.count() }}, Points {{ points.count() }}</p>
`,
})
export class App {
protected readonly counter = inject(Counter);
protected readonly score = inject(Score);
protected readonly points = inject(Points);
}
Click Add. The page shows:
Add
Counter 1, Score 1, Points 0
What’s next
We now have services that hold signals and a way to share them across the app. In Part 15, we’ll build a small store on that: a service with a private writable signal, read-only views for components, and methods as the only way to change it.