So far Jali's menu has been written straight into the class. In a real app, the names, prices and stock live on a server and can change every hour. The page has to ask for them first.
For that, Angular has HttpClient: a built-in service for sending HTTP requests (requests to a server, such as GET, POST, PUT, DELETE) and reading the answers. Picture a waiter at Jali's Pancake Stall. You write your order on a slip, but the waiter only walks to the kitchen when you hand the slip over. Hand over two slips, and he walks twice. In Angular, the order slip is the Observable that http.get() makes, handing it over is subscribe(), and the waiter's walk to the kitchen is the request going to the server.
Setting up HttpClient
Since Angular 21, HttpClient is available without registering it. In an Angular CLI project, the provideHttpClient() line in app.config.ts is still used to add interceptors (code that runs on every request, with its own lesson later) or other options. In Angular 20 and older, this line is required:
import { ApplicationConfig } from '@angular/core'
import { provideHttpClient } from '@angular/common/http'
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient()],
}
In Angular 20 and older, if you forget this line, a service asking for HttpClient fails to be created. The console writes an NG0201 (No provider found for ...) naming HttpClient. In Angular 18, that error is called NullInjectorError. The exercise editor and the Playground add this line themselves as soon as the code mentions HttpClient.
GET from a service
The request goes in a service, like the cart in the Services and DI lesson, so any page can use it:
// src/app/menu-api.service.ts
import { Injectable, inject } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { Observable } from 'rxjs'
export interface Menu {
id: number
name: string
price: number
stock: number
}
@Injectable({ providedIn: 'root' })
export class MenuApi {
private http = inject(HttpClient)
getMenu(): Observable<Menu[]> {
return this.http.get<Menu[]>('/api/menu')
}
}
The server answers with JSON (text holding data, written like a JavaScript object), and HttpClient turns it into a JavaScript array:
[
{ "id": 1, "name": "Chocolate Cheese Pancake", "price": 8, "stock": 4 },
{ "id": 2, "name": "Special Egg Pancake", "price": 10, "stock": 6 },
{ "id": 3, "name": "Pandan Pancake", "price": 7, "stock": 0 }
]
inject(HttpClient)asks forHttpClient, the same as asking for any other service.this.http.get<Menu[]>('/api/menu')prepares a GET request to the address/api/menuand returns anObservable<Menu[]>. The request is not sent yet.<Menu[]>is only a promise to TypeScript about the answer's shape: an array ofMenu, asinterface Menudescribes. Angular doesn't check it. If the server sends"price": "10", the value is still text.
Showing it: loading, data, error
This component uses MenuApi. Its load() method runs once in the constructor, then again each time the Reload button is clicked. The template shows one of three states: loading, data, or failed:
// src/app/menu/menu.ts
import { Component, inject, signal } from '@angular/core'
import { HttpErrorResponse } from '@angular/common/http'
import { MenuApi, type Menu } from '../menu-api.service'
@Component({
selector: 'app-menu',
standalone: true,
template: `
<button (click)="load()">Reload</button>
@if (loading()) {
<p>Loading menu...</p>
} @else if (error()) {
<p>Failed: {{ error() }}</p>
} @else {
@for (m of menu(); track m.id) {
<p>{{ m.name }}: {{ m.price }}</p>
} @empty {
<p>No menu yet.</p>
}
}
`,
})
export class MenuPage {
private api = inject(MenuApi)
menu = signal<Menu[]>([])
loading = signal(true)
error = signal('')
constructor() {
this.load()
}
load() {
this.loading.set(true)
this.error.set('')
this.api.getMenu().subscribe({
next: (data) => {
this.menu.set(data)
this.loading.set(false)
},
error: (err: HttpErrorResponse) => {
this.error.set(err.message)
this.loading.set(false)
},
})
}
}
| When | What shows |
|---|---|
| The request has just been sent | Loading menu... |
| The server answers 200 (success) | three lines, starting with Chocolate Cheese Pancake: 8 |
| The server can't be reached | Failed: Http failure response for /api/menu: 0 undefined |
subscribe({ next, error })splits the success path from the failure path.erris anHttpErrorResponse.err.statusholds the status code: 0 when the server can't be reached at all, 404 when the address doesn't exist.err.messageholds a sentence like the one in the table. The end of that sentence,0 undefined, comes from thefetchbackend (the part that actually sends the request), the default since Angular 22. In Angular 21 and older, or withwithXhr()(an option to use the older backend), it ends in0 Unknown Error. Because the sentence differs between versions, it's safer to write your own sentence for users, for exampleerr.status === 0 ? 'The server cannot be reached' : err.message.loadingis switched off on both paths. Don't switch it off incomplete: a failed request never callscomplete, so the page would stay on "Loading menu..." forever.
Other options: httpResource, stable since Angular 22. The three signals above (menu, loading, error) and the load() method can be replaced by one property:
import { httpResource } from '@angular/common/http'
export class MenuPage {
menu = httpResource<Menu[]>(() => '/api/menu', { defaultValue: [] })
}
<button (click)="menu.reload()">Reload</button>
@if (menu.isLoading()) {
<p>Loading menu...</p>
} @else if (menu.error()) {
<p>Could not load the menu.</p>
} @else {
@for (m of menu.value(); track m.id) {
<p>{{ m.name }}: {{ m.price }}</p>
}
}
httpResource sends the GET as soon as the component is created. It already has the signals isLoading(), error() and value(), and a reload() method to load again. The template above checks error() first, because when the request fails, reading value() throws the error Resource is currently in an error state. Which way to pick:
| Way | When to pick it |
|---|---|
httpResource |
GET data that is shown on the page, such as the menu list. |
toSignal(this.api.getMenu(), { initialValue: [] }) from @angular/core/rxjs-interop |
Your service already returns an Observable, and you only need its value as a signal. |
subscribe (the way above) |
Actions sent when a button is clicked, such as POSTing an order, or when you need RxJS operators. |
No subscribe, no request
An Observable from HttpClient is cold: get() only prepares the request, and the request is sent only when something subscribes. Without subscribe(), 0 requests are sent and the page stays on "Loading menu...".
Also, every subscribe() sends a new request. Say getMenu() is subscribed twice: once for the list, and once more to count the menu items. That means 2 identical requests to the server. {{ (menu$ | async)?.length }} written twice in a template sends two requests too, because each async subscribes on its own (menu$ here is the Observable from getMenu()). So fetch once, keep the result in a signal, then read that signal anywhere.
Why does HttpClient use an Observable and not a Promise (JavaScript's built-in way to hold a value that arrives later)? First, an Observable can be cancelled: if the subscription stops before the server answers, HttpClient cancels the request. For example, the async pipe unsubscribes when its component is removed because you go to another page. Second, RxJS operators (map, catchError, retry) can go in its pipe().
catchError: a fallback when it fails
If a failure can simply become an empty list, put catchError in the service:
import { catchError, of } from 'rxjs'
getMenu(): Observable<Menu[]> {
return this.http.get<Menu[]>('/api/menu').pipe(
catchError(() => of([])),
)
}
When the server is down, catchError catches the error, then of([]) sends [] through next. The component gets an empty list, so @empty shows "No menu yet." The error part of subscribe is never called, so no failure message shows. This suits side sections of a page. For the main section, let the error reach the component, so buyers know something is wrong and can press Reload.
Other requests, such as a POST to send an order, look the same, and are also only sent when subscribed: this.http.post('/api/orders', { menuId: 2, quantity: 1 }).subscribe().
The exercise uses the same service pattern. ApiService has private http = inject(HttpClient) and a getData() returning this.http.get<any[]>('/api/data') (any[]: an array of anything). The component uses private api = inject(ApiService) and shows <p>Items: {{ items().length }}</p>.
⚠️ Requests that never go out, or go out twice
- Forgetting to subscribe.
get()withoutsubscribe()(orasync) sends nothing. - Subscribing twice. Each subscription sends one request. Keep the result in a signal and read it from there.
- Switching loading off in
complete. A failed request skipscomplete. Switch it off innextanderror. - Forgetting
provideHttpClient()in an Angular 20 or older CLI project: an NG0201 namingHttpClient(in Angular 18:NullInjectorError). Since Angular 21, this error no longer appears. - Exercise detail. Get
HttpClientandApiServicewithinject(), not through theconstructor, and keep the paragraph starting withItems:. The exercise editor has no server at/api/data. If you subscribe, the request fails with status 0 (Http failure response for /api/data: 0 undefined, because the editor runs Angular 22), and the paragraph stays atItems: 0. That's expected and isn't graded.
TL;DR: HttpClient is Angular's built-in service for sending HTTP requests (requests to a server). Since Angular 21, HttpClient is available without registering it. In Angular 20 and older, register it with provideHttpClient(). Put the request in a service: inject(HttpClient), then this.http.get<Menu[]>('/api/menu'). The result is a cold Observable: no subscribe(), no request, and every subscribe() sends a new one. Show the three states (loading, data, failed) with loading, menu and error signals. Switch loading off in both the next (success) and error (failure) parts of subscribe, not in complete, because a failed request never calls complete. catchError(() => of([])) swaps a failure for a fallback, here an empty list. HttpClient uses Observables because a request can be cancelled and shaped with RxJS operators.
⚡ GET from a service
Write:
@Injectable({ providedIn: 'root' })
export class MenuApi {
private http = inject(HttpClient)
getMenu(): Observable<Menu[]> {
return this.http.get<Menu[]>('/api/menu')
}
}
Meaning: HttpClient is Angular's built-in service for sending HTTP requests to a server, and MenuApi asks for it with inject(). get() only prepares a GET request to /api/menu and returns an Observable: the request isn't sent yet. <Menu[]> is a promise to TypeScript about the answer's shape (an array of Menu, the data of one menu item), not a check.
In the exercise, the service is called ApiService. Get HttpClient and ApiService with inject(), not through the constructor. The editor has no server at /api/data, so the paragraph stays at Items: 0, and that's expected.
⚡ No subscribe, no request
Write:
this.api.getMenu().subscribe({
next: (data) => this.menu.set(data),
error: (err: HttpErrorResponse) => this.error.set(err.message),
})
Guess first: getMenu() is subscribed twice, once for the list and once to count the items. How many requests go out?
Two identical requests. Every subscribe() sends a new request, and without subscribe() there's no request at all. Fetch once and keep the result in a signal.
Meaning: Here the component subscribes to getMenu() from MenuApi, the service in the step before. In subscribe, next is the success path (the data goes into the menu signal), and error is the failure path (the message goes into the error signal). If there's a loading signal for the "Loading menu..." text, switch it off on both paths, not in complete, because a failed request never calls complete.
⚡ An Observable can be cancelled
Write:
return this.http.get<Menu[]>('/api/menu').pipe(
catchError(() => of([])),
)
Meaning: HttpClient uses Observables for two reasons. First, a request can be cancelled: if the subscription stops before the server answers, the request is cancelled. Second, RxJS operators (functions that work on each value) can go in pipe(), like catchError in this code: if the request fails, of([]) sends an empty list instead.