The menu card has an Order button, and OrderSummary, the order summary in the corner of the page, needs to know what's in the cart. With inputs and outputs, the news has to go up from the card to App through an output first, then come down again to OrderSummary through an input. The more components there are, the longer that relay gets: the news is passed from component to component.
A service makes the relay unnecessary. A service is a plain class that holds data or logic that many components share. Dependency injection (DI) is how Angular delivers that service to the components that ask for it. Picture Jali's Pancake Stall with one order book on the cashier's desk. The cook and the person taking orders don't each carry their own book. They ask Jali for the same one. The book is the service, and the cook and the person taking orders are components. Jali, who hands the book out, is the injector (the part of Angular that creates services and hands them out). Asking for the book is calling inject().
A service: a class with @Injectable
This cart service keeps the list of pancakes ordered:
// src/app/cart.service.ts
import { Injectable, signal } from '@angular/core'
@Injectable({ providedIn: 'root' })
export class CartService {
items = signal<string[]>([])
add(name: string) {
this.items.update((items) => [...items, name])
}
}
@Injectable()marks this class as a service Angular can inject into (hand to) components.providedIn: 'root'registers it in the root injector, the injector of the whole app. The result is one instance for the whole app, created the first time someone asks for it. The service needs no registering anywhere else.- In Angular 22, the command
ng generate servicewrites@Service(), not@Injectable. It means the same as@Injectable({ providedIn: 'root' }), with one condition: the service must get its dependencies (other services it needs) withinject(), not through theconstructor(the function that runs when an instance of the class is created).@Injectableis still used in older code, for constructor injection (covered below), and forproviderswithuseClass. This lesson and its exercise use@Injectable({ providedIn: 'root' }), which works in every version. - Apart from that,
CartServiceis a plain class: anitemsproperty and anadd()method, no template. itemsis a signal, andadd()builds a new array withupdate. Since Angular 22, components use OnPush by default: a component is only redrawn when something tells it to, such as a signal its template reads changing. Ifitemsis a plain array changed withpush, OrderSummary is never told and keeps showing 0.
inject(): asking for a service
The menu card asks for that service, then calls add() when the Order button is clicked:
// src/app/menu-item/menu-item.ts
import { Component, Input, inject } from '@angular/core'
import { CartService } from '../cart.service'
@Component({
selector: 'app-menu-item',
standalone: true,
template: `
<h3>{{ name }}</h3>
<button (click)="order()">Order</button>
`,
})
export class MenuItem {
@Input() name = ''
private cart = inject(CartService)
order() {
this.cart.add(this.name)
}
}
The OrderSummary component asks for the same service, then shows how many items it holds:
// src/app/order-summary/order-summary.ts
import { Component, inject } from '@angular/core'
import { CartService } from '../cart.service'
@Component({
selector: 'app-order-summary',
standalone: true,
template: `<p>Items in cart: {{ cart.items().length }}</p>`,
})
export class OrderSummary {
cart = inject(CartService)
}
inject(CartService)asks Angular for the service. Write it on a property as above, or inside theconstructor. Angular creates the instance, so you never writenew.privatein MenuItem meanscartcan only be used inside the MenuItem class.- An older form you'll still meet often, with the same result, is constructor injection:
constructor(private cart: CartService) {}. - MenuItem and OrderSummary don't use each other, and there's no input or output between them. App's template is just
<app-menu-item name="Special Egg Pancake" />and<app-order-summary />. The two components share data through the service.
| What happens | cart.items() |
OrderSummary shows |
|---|---|---|
| The page first shows | [] |
Items in cart: 0 |
| Click Order on the Special Egg Pancake card | ['Special Egg Pancake'] |
Items in cart: 1 |
| Click Order once more | two names | Items in cart: 2 |
The exercise uses the same pattern. DataService, marked @Injectable({ providedIn: 'root' }), has a getMessage() that returns 'Data from the service!'. The component writes private data = inject(DataService) and then message = this.data.getMessage(), and its template is <p>{{ message }}</p>.
One instance for everyone
Say MenuItem and OrderSummary each write cart = new CartService(). Then each component has its own cart. MenuItem adds to its own cart, while OrderSummary reads its own, which is still empty. So after two clicks on Order, OrderSummary still shows Items in cart: 0.
With inject() and providedIn: 'root', Angular hands the same instance to everyone who asks:
| How the cart is obtained | Number of instances | OrderSummary after 2 clicks |
|---|---|---|
new CartService() in each component |
one per component | Items in cart: 0 |
inject(CartService) + providedIn: 'root' |
one for everyone | Items in cart: 2 |
So the parts of a page that use the same data (the cart, the logged-in account, data from the server) stay in sync: they always show the same thing.
providers on a component: its own instance
Sometimes you do want separate instances. Register the service in the component's providers:
@Component({
selector: 'app-menu-item',
standalone: true,
providers: [CartService],
template: `...`,
})
export class MenuItem { /* same as before */ }
When a component asks for a service, Angular looks for it from that component upwards: its own providers first, then its parent's, and the root injector last. With the line providers: [CartService], every MenuItem card gets a new cart. Say you click Order twice on the first card and once on the second. The first card's cart holds 2 items, the second 1, and OrderSummary (which has no providers) uses the root instance, still at 0.
When the service can't be found
With no providedIn, and the service registered in no providers anywhere, Angular has no recipe for building it. The component asking for it fails to be created, and the console writes:
ERROR NG0201: No provider found for `CartService`. Source: Environment Injector. Find more at https://v22.angular.dev/errors/NG0201
You get the same when the class has no @Injectable() at all. Angular 18 writes the same error under another name: NullInjectorError: No provider for CartService!. The fix: add { providedIn: 'root' }, or register it in providers.
inject() may also only be called while Angular is creating something: on a class property or in the constructor. If you call it inside a method that runs on a click, you get this error:
NG0203: The `CartService` 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
Why ask instead of building it yourself
A component using inject() only asks for a cart; it doesn't decide where the cart comes from. So in a test (code that checks your code), you can swap it for a fake cart without changing a single line of OrderSummary. In the code below, the providers in the test settings give a fake object as CartService:
TestBed.configureTestingModule({
imports: [OrderSummary],
providers: [{ provide: CartService, useValue: { items: signal(['Special Egg Pancake']), add() {} } }],
})
OrderSummary in this test shows Items in cart: 1. Being able to swap the service is the main benefit of DI: testability (easy to test). Another benefit is loose coupling: the component isn't tied to how the service is built.
⚠️ When the cart doesn't connect across components
newin each component. Eachnewmakes its own copy, so data never reaches the other component. Ask throughinject().- Forgetting
providedIn: 'root'.@Injectable()alone registers nothing:NG0201: No provider found for CartService(in Angular 18:NullInjectorError: No provider for CartService!). - Shared data in a plain property.
items: string[] = []withpushtells nobody, so other components (OnPush since Angular 22) keep showing the old contents. Keep it in a signal. providers: [CartService]on a component without meaning to. That component and its children get a new instance, separate from root.- Exercise detail. The grader looks for a call like
= this.data.getMessage(, so keep the service in a property first, then call its method.inject(DataService).getMessage()on one line, or the textData from the service!typed into the template, isn't accepted.
TL;DR: A service is a class that holds data or logic for many components, marked @Injectable({ providedIn: 'root' }). In Angular 22, ng generate service writes @Service(), which means the same. Dependency injection (DI) is how Angular delivers services: components ask for one with inject(CartService) (or through the constructor), not by building it with new. With providedIn: 'root', everyone who asks gets one and the same instance, so an order from the menu card (MenuItem) appears in the order summary (OrderSummary) right away. providers: [CartService] on a component gives that component its own instance. Keep shared data in a signal, so other components get redrawn. An unregistered service throws NG0201 (No provider found for ...; in Angular 18 NullInjectorError), and inject() inside a method throws NG0203. Because components only ask, the service can be swapped for a fake in tests (code that checks your code): that's testability (easy to test).
⚡ A service: a class with @Injectable
Write:
@Injectable({ providedIn: 'root' })
export class CartService {
items = signal<string[]>([])
add(name: string) {
this.items.update((items) => [...items, name])
}
}
Meaning: This is a service: a plain class that holds data for many components, here what's in the cart. providedIn: 'root' registers it once for the whole app, with no registering anywhere else. Without providedIn: 'root', the console writes NG0201. The data lives in a signal, so other components get redrawn when it changes.
⚡ Ask with inject(), not new
Write:
export class OrderSummary {
cart = inject(CartService)
}
Guess first: the menu card (MenuItem) adds a pancake to the cart when Order is clicked, and OrderSummary shows how many items the cart holds. If each of them writes new CartService(), how many items does OrderSummary show after Order is clicked twice?
It shows 0. Each new makes its own cart, so MenuItem fills its cart while OrderSummary reads its own, still empty. With inject() and providedIn: 'root', everyone gets the same instance: 2.
Meaning: inject(CartService) asks Angular for the service. Angular creates the instance; you only ask for it, so there's no new. In the exercise, the service is DataService: keep it in a property first (private data = inject(DataService)), then call its method, message = this.data.getMessage().
⚡ The main benefit: testability
Write:
providers: [{ provide: CartService, useValue: { items: signal(['Special Egg Pancake']), add() {} } }],
Meaning: This line is in a test's settings (code that checks your code). When something asks for CartService, Angular gives this fake object instead, with a cart holding one pancake. Because the component only asks, the service can be swapped without changing a single line of OrderSummary. That's the main benefit of dependency injection: testability (easy to test).