Share one cart between components with a service. This part covers @Service, inject(), how Angular finds a service, providers for a copy per component, and reading NG0201 and NG0203.
Two components often need the same thing. A header badge and a product list both need the cart. Every component that logs needs the logger. If each component makes its own, they don’t share anything. Angular’s answer is dependency injection, or DI: a component asks for what it needs, and Angular hands it over.
This part covers services with @Service(), asking for them with inject(), how Angular finds what you asked for, and providers for a separate copy per component. In Part 10 we used inject() without explaining it, and in Part 8 and Part 10 we met error NG0203. Here’s what was going on. 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
This shop has a cart, a badge that shows how many items are in it, and a product list with Add buttons. Make the four files below. The cart is a plain class that keeps a list of names in a signal, like the cart in Part 3.
// src/app/cart.ts
import { signal } from '@angular/core';
export class Cart {
readonly items = signal<string[]>([]);
add(name: string) {
this.items.update((list) => [...list, name]);
}
}
The badge and the list each make a cart with new Cart():
// src/app/cart-badge.ts
import { Component } from '@angular/core';
import { Cart } from './cart';
@Component({
selector: 'app-cart-badge',
template: `<p>Cart: {{ cart.items().length }} items</p>`,
})
export class CartBadge {
protected readonly cart = new Cart();
}
// src/app/product-list.ts
import { Component } from '@angular/core';
import { Cart } from './cart';
@Component({
selector: 'app-product-list',
template: `
<button (click)="cart.add('Apple')">Add apple</button>
<button (click)="cart.add('Bread')">Add bread</button>
<p>Added here: {{ cart.items().join(', ') }}</p>
`,
})
export class ProductList {
protected readonly cart = new Cart();
}
// src/app/app.ts
import { Component } from '@angular/core';
import { CartBadge } from './cart-badge';
import { ProductList } from './product-list';
@Component({
selector: 'app-root',
imports: [CartBadge, ProductList],
template: `
<app-cart-badge />
<app-product-list />
`,
})
export class App {}
Before you read on, guess. Click Add apple, then Add bread. What does the badge say?
The page shows:
Cart: 0 items
Add appleAdd bread
Added here: Apple, Bread
(The two buttons read Add appleAdd bread because buttons sit on one line, and the page text runs them together.)
The list added two things. The badge still says 0.
Why there are two carts
new Cart() makes a new object every time it runs. It ran twice, once in each component, so there are two carts. The list added to its own cart. The badge is reading a different one that nobody touched. Both signals work fine. They’re just two separate signals.
One fix is to make the cart in App and pass it down with an input, as in Part 5. That works for one level. In a real app, the badge sits inside a header, inside a toolbar, and the list sits inside a page, inside a layout. Every component in between would need a cart input it never uses, only to pass it on. Add a logger and a user session, and every component carries three inputs it doesn’t care about.
What we want is for any component to say “I need the cart” and get the cart. That’s what DI does.
@Service() and inject(): ask, don’t make
Two changes. First, mark Cart as a service with @Service(). A service is a class that holds something to share, like data or helper methods, rather than drawing part of the page. Second, in the components, replace new Cart() with inject(Cart).
Here are the three changed files. app.ts stays the same. We added a console.log to the cart’s constructor, the function that runs when an object is made, so we can see how many carts there are.
// src/app/cart.ts
import { Service, signal } from '@angular/core';
@Service()
export class Cart {
readonly items = signal<string[]>([]);
constructor() {
console.log('Cart created');
}
add(name: string) {
this.items.update((list) => [...list, name]);
}
}
// src/app/cart-badge.ts
import { Component, inject } from '@angular/core';
import { Cart } from './cart';
@Component({
selector: 'app-cart-badge',
template: `<p>Cart: {{ cart.items().length }} items</p>`,
})
export class CartBadge {
protected readonly cart = inject(Cart);
}
// src/app/product-list.ts
import { Component, inject } from '@angular/core';
import { Cart } from './cart';
@Component({
selector: 'app-product-list',
template: `
<button (click)="cart.add('Apple')">Add apple</button>
<button (click)="cart.add('Bread')">Add bread</button>
<p>Added here: {{ cart.items().join(', ') }}</p>
`,
})
export class ProductList {
protected readonly cart = inject(Cart);
}
When the page loads, the console shows one line, not two:
Cart created
Click Add apple, then Add bread. The page shows:
Cart: 2 items
Add appleAdd bread
Added here: Apple, Bread
The badge updates, because both components hold the same cart, and so read the same items signal.
Here’s what each piece does:
@Service()is a decorator, like@Component. It tells Angular “this class can be handed out”. With no options, the service is automatically provided: Angular makes it available to the whole app, and makes one instance of it, the first time something asks. You importServicefrom@angular/core. It’s new in Angular 22.inject(Cart)asks Angular for aCart. The class itself is the key you ask with. If a cart exists, you get it. If not, Angular makes one, keeps it, and gives you that.- The field is
readonly, like a signal field. You never point it at a different cart.
To make a service file, you can also run ng generate service cart in your project folder. It writes src/app/cart.ts with an empty @Service() class named Cart, and a test file next to it.
Services hold signals
Our cart keeps its list in a signal. That’s what makes the badge update: the badge’s template read items(), so when the list’s Add button changes items, Angular redraws the badge too, even though the click happened in another component. A signal in a service works exactly like a signal in a component. It doesn’t matter where the signal lives, only who reads it.
Right now any component could call cart.items.set([]) and wipe the cart. The worked example below makes the writable signal private and hands out a read-only view. Part 15 builds a whole store this way.
inject() only works while Angular is building something
inject() has to run while Angular is creating the component or service: in a field initializer, as above, or in the constructor. Angular calls that time an injection context. We met it in Part 8, where effect() had the same rule. During it, Angular knows which component is asking, and that’s how it knows where to look.
A click handler runs long after the component was made, so this fails:
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { Cart } from './cart';
import { CartBadge } from './cart-badge';
@Component({
selector: 'app-root',
imports: [CartBadge],
template: `
<app-cart-badge />
<button (click)="addApple()">Add apple</button>
`,
})
export class App {
protected addApple() {
inject(Cart).add('Apple');
}
}
It builds. Click Add apple, and the browser console shows an error:
Cart created
ERROR RuntimeError: NG0203: The `_Cart` token injection failed. `inject()` function must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`. Find more at https://v22.angular.dev/errors/NG0203
The message lists the places that are an injection context. The _Cart is our Cart. In the development build, the build tool compiles our class as var Cart = class _Cart {...}, so the class reports its own name as _Cart. It does this to any class that refers to itself, and Angular’s compiled code makes every service and component do that. The fix is the pattern from the start of this part: inject in a field, and use the field in the handler.
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { Cart } from './cart';
import { CartBadge } from './cart-badge';
@Component({
selector: 'app-root',
imports: [CartBadge],
template: `
<app-cart-badge />
<button (click)="addApple()">Add apple</button>
`,
})
export class App {
private readonly cart = inject(Cart);
protected addApple() {
this.cart.add('Apple');
}
}
Click Add apple. The page shows:
Cart: 1 items
Add apple
The field is private this time, because the template doesn’t use it. Only the method does.
How inject() finds a service
Angular keeps services in injectors. An injector is a box of things that can be handed out, with a list of how to make each one. There’s one for the whole app, called the root injector. The root injector can make any @Service() class. Each component gets its own small injector too, called an element injector. It usually has no providers of yours.
When a component calls inject(X), Angular asks the component’s own injector first. If X isn’t there, it asks the parent component’s injector, then that one’s parent, all the way up. If nothing in the component tree has X, it asks the root injector. The first injector that has X wins.
The next animation follows one inject() call through three components: App, a CounterPanel inside it, and a CounterDisplay inside that. The display asks for a Counter service. The blue arrows are the search. The black arrow is the service coming back. A green box has a Counter.
inject() asks the nearest injector first and walks up. The first one that has the service wins.
Here are those steps in words, in case the animation doesn’t play for you:
CounterDisplayis being created, and its field initializer callsinject(Counter).- Angular looks in
CounterDisplay‘s own element injector. It has no providers, so there’s noCounterthere. - It moves up to the parent,
CounterPanel, then toApp. Neither lists aCounter. - It reaches the root injector.
Counteris an@Service(), so the root injector has it. It makes the oneCounterif it doesn’t exist yet and hands it back. Any other component asking forCountergets this same one. - Now change one thing:
CounterPanellistsproviders: [Counter]. The search finds aCounterinCounterPanel‘s injector and stops there.CounterDisplaygetsCounterPanel‘s ownCounter, and the root one isn’t used.
providers: a copy for each component
The last step of that animation is how you get a separate copy. A component’s providers array lists services its element injector should make. Each instance of the component gets its own copy, and the components inside it find that copy first.
Here’s the code from the animation. The Counter service:
// src/app/counter.ts
import { Service, signal } from '@angular/core';
@Service()
export class Counter {
readonly count = signal(0);
increment() {
this.count.update((n) => n + 1);
}
}
CounterDisplay only shows the count it finds:
// src/app/counter-display.ts
import { Component, inject } from '@angular/core';
import { Counter } from './counter';
@Component({
selector: 'app-counter-display',
template: `<p>Count: {{ counter.count() }}</p>`,
})
export class CounterDisplay {
protected readonly counter = inject(Counter);
}
CounterPanel lists providers: [Counter], has a button, and shows a CounterDisplay inside it. Its name is an input from Part 5:
// src/app/counter-panel.ts
import { Component, inject, input } from '@angular/core';
import { Counter } from './counter';
import { CounterDisplay } from './counter-display';
@Component({
selector: 'app-counter-panel',
imports: [CounterDisplay],
providers: [Counter],
template: `
<button (click)="counter.increment()">Add one to {{ name() }}</button>
<app-counter-display />
`,
})
export class CounterPanel {
readonly name = input.required<string>();
protected readonly counter = inject(Counter);
}
App shows two panels, and one CounterDisplay of its own, outside both panels:
// src/app/app.ts
import { Component } from '@angular/core';
import { CounterDisplay } from './counter-display';
import { CounterPanel } from './counter-panel';
@Component({
selector: 'app-root',
imports: [CounterPanel, CounterDisplay],
template: `
<app-counter-panel name="A" />
<app-counter-panel name="B" />
<app-counter-display />
`,
})
export class App {}
Before you click anything, guess how many Counter objects there are. Then click Add one to A twice and Add one to B once. The page shows:
Add one to A
Count: 2
Add one to B
Count: 1
Count: 0
There are three counters. Panel A made one, and the display inside A found it. Panel B made another. The last display isn’t inside a panel, so its search went past App to the root injector and got the app-wide Counter, which nobody changed.
A copy in providers lives as long as the component that made it. Show the panel again later and it starts from 0.
Explain it like I’m ten
Think of a school. Every classroom has a supply cupboard, and the school has a big store room.
When you need scissors, you don’t bring your own from home. You ask. The teacher checks your classroom cupboard first. If the scissors aren’t there, someone fetches them from the store room. That’s inject(): you ask, and the nearest place that has it gives it to you.
The store room has one big stapler for the whole school. Every class that asks gets that same stapler. That’s an @Service(): one copy, shared by everyone.
Your classroom might keep its own glue in its cupboard. Then your class uses that glue, and it never goes to the store room for glue. Another class with its own glue uses theirs. That’s providers on a component.
The precise version
Angular has a tree of element injectors that follows how components are nested in your templates, plus the root injector above it. Each component has an element injector built from its providers array. inject(X), called in an injection context, starts at the current component’s element injector and walks up through each parent’s. If none has a provider for X, it asks the root injector, which knows every class marked @Service(). The first injector with a provider for X returns its instance, and makes it on the first request. An element injector makes one instance per component instance, and drops it when that component is destroyed. The root injector makes one instance for the whole app.
Where the analogy breaks: a stapler can only be in one classroom at a time, but a service is shared: every component that gets it holds the very same object at once, and a change one makes is seen by all of them. The store room also doesn’t keep the stapler on the shelf from the start. Angular makes a service only when something first asks for it. A service nobody injects is never made.
@Service({ autoProvided: false }): only where you list it
Some services only make sense per component, like the state of one form or one panel. You don’t want a stray app-wide copy that someone gets by forgetting providers. For those, write:
@Service({ autoProvided: false })
export class Draft {}
The root injector doesn’t know this class. Angular only makes it where a component lists it in providers. If you forget, inject() fails. The second worked example shows that error.
Worked example: a shop with a shared cart
Let’s build the shop properly. There’s a product list with prices, a header with a badge, and a summary with a Clear button. All three use one Cart. This time the cart keeps its writable signal private, and hands out a read-only view with asReadonly() from Part 3. Components can read items, but only the cart’s methods can change it.
// src/app/cart.ts
import { Service, computed, signal } from '@angular/core';
export interface Product {
name: string;
price: number;
}
@Service()
export class Cart {
private readonly state = signal<Product[]>([]);
readonly items = this.state.asReadonly();
readonly count = computed(() => this.state().length);
readonly total = computed(() => this.state().reduce((sum, p) => sum + p.price, 0));
add(product: Product) {
this.state.update((list) => [...list, product]);
}
clear() {
this.state.set([]);
}
}
The list shows each product with an Add button. export interface Product lets other files use the type:
// src/app/product-list.ts
import { Component, inject } from '@angular/core';
import { Cart, Product } from './cart';
@Component({
selector: 'app-product-list',
template: `
@for (product of products; track product.name) {
<button (click)="cart.add(product)">Add {{ product.name }} ({{ product.price }})</button>
}
`,
})
export class ProductList {
protected readonly cart = inject(Cart);
protected readonly products: Product[] = [
{ name: 'Apple', price: 2 },
{ name: 'Bread', price: 3 },
];
}
The header only reads:
// src/app/shop-header.ts
import { Component, inject } from '@angular/core';
import { Cart } from './cart';
@Component({
selector: 'app-shop-header',
template: `<h1>Shop ({{ cart.count() }} in cart)</h1>`,
})
export class ShopHeader {
protected readonly cart = inject(Cart);
}
The summary lists what’s in the cart and can empty it. Its names is a computed that reads a signal from the service. That works like any other computed:
// src/app/cart-summary.ts
import { Component, computed, inject } from '@angular/core';
import { Cart } from './cart';
@Component({
selector: 'app-cart-summary',
template: `
<p>In cart: {{ names() }}</p>
<p>Total: {{ cart.total() }}</p>
<button (click)="cart.clear()">Clear</button>
`,
})
export class CartSummary {
protected readonly cart = inject(Cart);
protected readonly names = computed(() =>
this.cart
.items()
.map((p) => p.name)
.join(', '),
);
}
// src/app/app.ts
import { Component } from '@angular/core';
import { CartSummary } from './cart-summary';
import { ProductList } from './product-list';
import { ShopHeader } from './shop-header';
@Component({
selector: 'app-root',
imports: [ShopHeader, ProductList, CartSummary],
template: `
<app-shop-header />
<app-product-list />
<app-cart-summary />
`,
})
export class App {}
Click Add Apple (2), Add Bread (3) and Add Apple (2). The page shows:
Shop (3 in cart)
Add Apple (2)Add Bread (3)
In cart: Apple, Bread, Apple
Total: 7
Clear
Click Clear:
Shop (0 in cart)
Add Apple (2)Add Bread (3)
In cart:
Total: 0
Clear
Notice what isn’t here. App knows nothing about the cart. No component passes it to another. The header and the summary don’t know the list exists. Each one asks for the cart and reads its signals. Moving the badge into a toolbar later changes nothing about the cart.
Worked example: a draft per editor, and NG0201
A notes page lets you open several editors. Each editor keeps its own draft text and a word count. The draft is state for one editor, so we make it autoProvided: false:
// src/app/draft.ts
import { Service, computed, signal } from '@angular/core';
@Service({ autoProvided: false })
export class Draft {
readonly text = signal('');
readonly words = computed(() => {
const parts = this.text().split(' ');
return parts.filter((w) => w !== '').length;
});
}
The editor injects it. (input) and $event.target.value are from Part 2:
// src/app/note-editor.ts
import { Component, inject, input } from '@angular/core';
import { Draft } from './draft';
@Component({
selector: 'app-note-editor',
template: `
<label>{{ title() }} <input (input)="draft.text.set($event.target.value)" /></label>
<p>{{ draft.words() }} words</p>
`,
})
export class NoteEditor {
readonly title = input.required<string>();
protected readonly draft = inject(Draft);
}
App adds an editor each time you click New note:
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { NoteEditor } from './note-editor';
@Component({
selector: 'app-root',
imports: [NoteEditor],
template: `
<p><button (click)="addNote()">New note</button></p>
@for (n of notes(); track n) {
<app-note-editor [title]="'Note ' + n" />
}
`,
})
export class App {
protected readonly notes = signal<number[]>([]);
protected addNote() {
this.notes.update((list) => [...list, list.length + 1]);
}
}
It builds, and the page shows the button. Click New note. No editor appears, and the console shows:
ERROR ɵNotFound: NG0201: No provider found for `_Draft`. Source: Environment Injector. Find more at https://v22.angular.dev/errors/NG0201
followed by a list of lines starting with at. The page still shows only the button:
New note
Read it piece by piece:
NG0201is Angular’s code for “nothing could give me this”. The link at the end explains it on angular.dev.No provider found foris followed by what was asked for._Draftis ourDraftclass, named by the build tool the same way as_Cartearlier.Source: Environment Injectorsays where the search ended. It walked up from the editor, found noDraftin any component, and reached the root injector, which is a kind of environment injector. It doesn’t knowDrafteither, because ofautoProvided: false. Part 14 covers environment injectors.- The lines starting with
atare the stack trace: which functions were running. The top ones are inside Angular, so they don’t help much here.
The editor didn’t appear because Angular couldn’t make it without a Draft. Angular can’t tell at build time that you’ll forget providers, so this one only shows up when the component is created. The fix is one line in the editor, providers: [Draft]:
// src/app/note-editor.ts
import { Component, inject, input } from '@angular/core';
import { Draft } from './draft';
@Component({
selector: 'app-note-editor',
providers: [Draft],
template: `
<label>{{ title() }} <input (input)="draft.text.set($event.target.value)" /></label>
<p>{{ draft.words() }} words</p>
`,
})
export class NoteEditor {
readonly title = input.required<string>();
protected readonly draft = inject(Draft);
}
Click New note twice, and type buy milk today into Note 1 and call Ana into Note 2. The page shows:
New note
Note 1
3 words
Note 2
2 words
(The text you type is inside the input boxes, so it isn’t part of the page text.) Each editor has its own Draft. With an app-wide Draft, both editors would show the same count.
In older code
Most Angular code and docs written before version 22 make a service with @Injectable, and many take services as constructor parameters:
// src/app/app.ts
import { Component, Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class Greeter {
greet(name: string) {
return `Hello, ${name}`;
}
}
@Component({
selector: 'app-root',
template: `<p>{{ message }}</p>`,
})
export class App {
protected readonly message: string;
constructor(greeter: Greeter) {
this.message = greeter.greet('Ana');
}
}
The page shows:
Hello, Ana
@Injectable({ providedIn: 'root' }) does what @Service() does: one copy, made on first use, available app-wide. @Injectable() with no providedIn is like @Service({ autoProvided: false }): it has to be listed in providers. @Injectable isn’t deprecated, and ng generate service cart --injectable still makes one. A constructor parameter with a service type, constructor(greeter: Greeter), means the same as inject(Greeter).
One difference matters when you move code over. An @Service() class can’t have constructor parameters at all, not even ones with a default value. Use inject() in fields instead. Here’s what happens if you try:
// src/app/app.ts
import { Component, Service, inject } from '@angular/core';
@Service()
export class Greeter {
greet(name: string) {
return `Hello, ${name}`;
}
}
@Service()
export class Welcome {
constructor(private greeter: Greeter) {}
}
@Component({
selector: 'app-root',
template: `<p>Hi</p>`,
})
export class App {
protected readonly welcome = inject(Welcome);
}
✘ [ERROR] NG2028: @Service class cannot use constructor dependency injection. Use the `inject` function instead. [plugin angular-compiler]
The fix is in the message: private readonly greeter = inject(Greeter); as a field.
Best practices
- Make shared things a service and
inject()them. Every component that asks gets the same instance. It replacesnewin each component and inputs passed through components that don’t use them. - Use
@Service()for new services. One app-wide copy, with noprovidersto remember. It replaces@Injectable({ providedIn: 'root' }). - Use
providers: [X]for state that belongs to one component. Each instance gets its own copy, shared with the components inside it, and dropped with it. Mark such servicesautoProvided: falseso nobody gets an app-wide one by mistake. - Call
inject()in a field initializer.protected readonly cart = inject(Cart);sits at the top of the class, where a reader looks for what it needs. It replaces constructor parameters. - Keep a service’s writable signals
private. Hand outasReadonly()views and methods that change them, so every change goes through the service. - Lean on DI in tests. Because a component asks for its services instead of making them, a test can give it a fake one. Part 24 shows how.
Tips and traps
newon a service.new Cart()builds a separate object that nobody else sees. Nothing errors, but other components don’t update. Useinject(Cart).providers: [Cart]on a component by accident. That component and its children get their own cart, separate from everyone else’s. It looks like the same “doesn’t update” bug. Remove it, unless you meant a separate copy.inject()in a click handler or asetTimeout. The console showsNG0203: ... must be called from an injection context. Inject in a field and use the field.autoProvided: falsewithoutproviders. The console showsNG0201: No provider found for ...when the component is created, and the component doesn’t appear. Add the service to theprovidersof the component that owns it.- Constructor parameters in an
@Service()class. The build fails with NG2028, for any parameter, even one with a default value. Useinject()in a field. - Names like
_Cartin errors. That’s your classCart: the development build compiles it asclass _Cart. Search your code forCart.
A component asks for what it needs with inject(), and Angular hands over the nearest copy it can find.
Exercises
Exercise 1. Here the badge never changes. Click Add apple and see. Why? Fix it by deleting one line.
// src/app/cart.ts
import { Service, signal } from '@angular/core';
@Service()
export class Cart {
readonly items = signal<string[]>([]);
add(name: string) {
this.items.update((list) => [...list, name]);
}
}
// src/app/cart-badge.ts
import { Component, inject } from '@angular/core';
import { Cart } from './cart';
@Component({
selector: 'app-cart-badge',
providers: [Cart],
template: `<p>Cart: {{ cart.items().length }} items</p>`,
})
export class CartBadge {
protected readonly cart = inject(Cart);
}
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { Cart } from './cart';
import { CartBadge } from './cart-badge';
@Component({
selector: 'app-root',
imports: [CartBadge],
template: `
<app-cart-badge />
<button (click)="cart.add('Apple')">Add apple</button>
`,
})
export class App {
protected readonly cart = inject(Cart);
}
Cart: 0 items
Add apple
Exercise 2. Write a Theme service with a dark signal that starts false and a toggle() method. Write a ThemeToggle component with a Switch theme button that calls toggle(). App shows the toggle and a line Theme: light or Theme: dark. After one click, the page should show Theme: dark.
Exercise 3. Without running it, what does this page show? Each Ticket takes the next number when it’s made.
// src/app/app.ts
import { Component, Service, inject } from '@angular/core';
@Service()
export class Ticket {
private static next = 1;
readonly id = Ticket.next++;
}
@Component({
selector: 'app-holder',
template: `<p>Holder: {{ ticket.id }}</p>`,
})
export class Holder {
protected readonly ticket = inject(Ticket);
}
@Component({
selector: 'app-room',
imports: [Holder],
providers: [Ticket],
template: `<app-holder /><app-holder />`,
})
export class Room {}
@Component({
selector: 'app-root',
imports: [Room, Holder],
template: `<app-holder /><app-room /><app-room />`,
})
export class App {}
static puts next on the class itself, so all tickets share one counter. next++ gives the current value, then adds one.
Answers
1. CartBadge lists providers: [Cart], so it gets its own cart from its own element injector. App‘s button adds to the root cart. Delete the providers line, and the badge’s search reaches the root injector and finds the same cart as App. cart.ts and app.ts stay as they were:
// src/app/cart.ts
import { Service, signal } from '@angular/core';
@Service()
export class Cart {
readonly items = signal<string[]>([]);
add(name: string) {
this.items.update((list) => [...list, name]);
}
}
// src/app/cart-badge.ts
import { Component, inject } from '@angular/core';
import { Cart } from './cart';
@Component({
selector: 'app-cart-badge',
template: `<p>Cart: {{ cart.items().length }} items</p>`,
})
export class CartBadge {
protected readonly cart = inject(Cart);
}
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { Cart } from './cart';
import { CartBadge } from './cart-badge';
@Component({
selector: 'app-root',
imports: [CartBadge],
template: `
<app-cart-badge />
<button (click)="cart.add('Apple')">Add apple</button>
`,
})
export class App {
protected readonly cart = inject(Cart);
}
Click Add apple. The page shows:
Cart: 1 items
Add apple
2. The service holds the signal. The toggle and App both inject it:
// src/app/theme.ts
import { Service, signal } from '@angular/core';
@Service()
export class Theme {
readonly dark = signal(false);
toggle() {
this.dark.update((d) => !d);
}
}
// src/app/theme-toggle.ts
import { Component, inject } from '@angular/core';
import { Theme } from './theme';
@Component({
selector: 'app-theme-toggle',
template: `<button (click)="theme.toggle()">Switch theme</button>`,
})
export class ThemeToggle {
protected readonly theme = inject(Theme);
}
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { Theme } from './theme';
import { ThemeToggle } from './theme-toggle';
@Component({
selector: 'app-root',
imports: [ThemeToggle],
template: `
<app-theme-toggle />
<p>Theme: {{ theme.dark() ? 'dark' : 'light' }}</p>
`,
})
export class App {
protected readonly theme = inject(Theme);
}
Click Switch theme. The page shows:
Switch theme
Theme: dark
3. The first holder isn’t inside a room, so it gets the root Ticket, number 1. Each room has providers: [Ticket], so each room has its own, and both holders in a room share it. The first room’s ticket is 2, the second’s is 3. Here’s the run:
// src/app/app.ts
import { Component, Service, inject } from '@angular/core';
@Service()
export class Ticket {
private static next = 1;
readonly id = Ticket.next++;
}
@Component({
selector: 'app-holder',
template: `<p>Holder: {{ ticket.id }}</p>`,
})
export class Holder {
protected readonly ticket = inject(Ticket);
}
@Component({
selector: 'app-room',
imports: [Holder],
providers: [Ticket],
template: `<app-holder /><app-holder />`,
})
export class Room {}
@Component({
selector: 'app-root',
imports: [Room, Holder],
template: `<app-holder /><app-room /><app-room />`,
})
export class App {}
Holder: 1
Holder: 2
Holder: 2
Holder: 3
Holder: 3
What’s next
So far a service has been a class that Angular makes with new. In Part 14, we’ll provide plain values and settings with InjectionToken, swap one class for another with useClass and useFactory, and control where the search starts and stops.