HttpClient loads and sends data. This part covers typed GET and POST requests, why nothing is sent until you subscribe, query params, functional interceptors, and showing an error when a request fails.
Most apps get their data from a server. A list of books, a user’s profile, a saved order: each one arrives over HTTP, the same way the browser loads a page. Angular’s tool for that is HttpClient.
This part covers HttpClient.get and post with typed responses, why a request isn’t sent until you subscribe, putting requests in a service, query params, interceptors that see every request, and errors. It builds on services and inject() from Part 13 and the store from Part 15. 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
We need some data to load. Make a file called books.json in your project’s public/ folder, next to favicon.ico. Anything in public/ is served as it is, so the app can load it from the address /books.json. It stands in for a real server in this part.
[
{ "id": 1, "title": "A Wizard of Earthsea", "author": "Ursula K. Le Guin" },
{ "id": 2, "title": "The Hobbit", "author": "J. R. R. Tolkien" },
{ "id": 3, "title": "Matilda", "author": "Roald Dahl" }
]
Now paste this into src/app/app.ts:
// src/app/app.ts
import { HttpClient } from '@angular/common/http';
import { Component, inject, signal } from '@angular/core';
interface Book {
id: number;
title: string;
author: string;
}
@Component({
selector: 'app-root',
template: `
<p>Books loaded: {{ books().length }}</p>
<button (click)="load()">Load books</button>
`,
})
export class App {
private readonly http = inject(HttpClient);
protected readonly books = signal<Book[]>([]);
protected load() {
this.http.get<Book[]>('/books.json');
console.log('load() finished');
}
}
Before you read on, guess. Click Load books and wait a second. What does the page say?
Here’s what happens. The page shows:
Books loaded: 0
Load books
and the console shows:
load() finished
Nothing was loaded. If you open the browser’s developer tools (F12) and look at the Network tab, you’ll see no request for books.json either. get() didn’t fail. It never started. And even if it had, we never told it what to do with the books.
HttpClient: asking for data
Here’s the version that works:
// src/app/app.ts
import { HttpClient } from '@angular/common/http';
import { Component, inject, signal } from '@angular/core';
interface Book {
id: number;
title: string;
author: string;
}
@Component({
selector: 'app-root',
template: `
<button (click)="load()">Load books</button>
<ul>
@for (book of books(); track book.id) {
<li>{{ book.title }} by {{ book.author }}</li>
}
</ul>
`,
})
export class App {
private readonly http = inject(HttpClient);
protected readonly books = signal<Book[]>([]);
protected load() {
this.http.get<Book[]>('/books.json').subscribe((books) => this.books.set(books));
}
}
Click Load books. The page shows:
Load books
A Wizard of Earthsea by Ursula K. Le Guin
The Hobbit by J. R. R. Tolkien
Matilda by Roald Dahl
Let’s go through it.
HttpClientcomes from@angular/common/http. It’s a service, so we get it withinject(), as in Part 13. The field isprivatebecause the template doesn’t use it.get<Book[]>('/books.json')describes a GET request for that address. The<Book[]>is a generic, as insignal<Book[]>from Part 3. It tells TypeScript what the response body will be: a list of books.HttpClientreads the body as JSON and turns it into JavaScript objects for you..subscribe(...)is the part we were missing. It sends the request, and gives us a function to call when the answer arrives. Our function puts the books into a signal, and the screen follows, as in Part 3.
We didn’t add anything to app.config.ts. In Angular 22, HttpClient is available to the whole app by default, like a @Service(), and it sends requests with the browser’s fetch. You’ll still see provideHttpClient() in app.config.ts, because that’s where you turn on extra features. We’ll need it for interceptors below.
The type is a promise, not a check
<Book[]> is something you tell TypeScript. Angular doesn’t check that the server really sent a list of books. If the server sends name where you said title, TypeScript is happy, and the page shows blanks. Exercise 3 shows what that looks like. Keep your interfaces in step with what the server really sends.
Observables: nothing happens until you subscribe
get() doesn’t return the books. It returns an Observable: an object that describes some work that produces values over time. It comes from a library called RxJS, which Angular uses for HTTP. An Observable doesn’t start the work when you make it. It starts when someone calls subscribe(), and each subscribe() starts its own run. People call that a cold Observable.
That’s why the first try did nothing. We made the Observable and threw it away. No one subscribed, so no request was sent.
An Observable from HttpClient is simple, as these things go:
- Each
subscribe()sends one request. Subscribe twice, and you send two. (Exercise 2 counts them.) - When the response arrives, it gives you one value, the body, and then finishes.
- If the request fails, it gives you an error instead.
You can hand subscribe() one function, as above, or an object with a next function for the value and an error function for a failure. We’ll use the second form for errors below.
Because the Observable finishes after one response, you don’t need to clean up after it. If the component is destroyed before the answer arrives, though, the next function still runs. Part 20 covers RxJS properly, including toSignal, and shows how to stop it with takeUntilDestroyed. For this part, all we need is: call subscribe, and get the value in a function.
Put requests in a service
A component shouldn’t know where its data comes from. If the address changes, or the server wants a header, you don’t want to hunt through every component that loads books. Put the requests in a service, and let components call it.
// src/app/book-api.ts
import { HttpClient } from '@angular/common/http';
import { Service, inject } from '@angular/core';
import { Observable } from 'rxjs';
export interface Book {
id: number;
title: string;
author: string;
}
@Service()
export class BookApi {
private readonly http = inject(HttpClient);
list(): Observable<Book[]> {
return this.http.get<Book[]>('/books.json');
}
}
// src/app/app.ts
import { Component, inject, signal } from '@angular/core';
import { Book, BookApi } from './book-api';
@Component({
selector: 'app-root',
template: `
<button (click)="load()">Load books</button>
<p>{{ books().length }} books</p>
`,
})
export class App {
private readonly api = inject(BookApi);
protected readonly books = signal<Book[]>([]);
protected load() {
this.api.list().subscribe((books) => this.books.set(books));
}
}
Click Load books. The page shows:
Load books
3 books
BookApi returns the Observable and doesn’t subscribe. That leaves the choice to the caller: when to send, and what to do with the answer. Observable<Book[]> is the return type, written out so anyone reading list() sees what it gives back. You import Observable from rxjs, which every Angular project already has.
The service only knows how to talk to the server. Where the books live once they’ve arrived, and whether they’re loading, is the job of the component or of a store like the one in Part 15.
Interceptors: code that sees every request
Say the server wants every request to carry a header that names the app. Or you want to log every request while you debug. You could add that to every call in every service. Or you could write it once, as an interceptor: a function that every request passes through on its way out, and every response passes through on its way back.
Here are two. Put them in a new file:
// src/app/interceptors.ts
import { HttpEventType, HttpInterceptorFn } from '@angular/common/http';
import { tap } from 'rxjs';
export const clientHeaderInterceptor: HttpInterceptorFn = (req, next) => {
const withHeader = req.clone({ setHeaders: { 'X-Client': 'reading-list' } });
return next(withHeader);
};
export const loggingInterceptor: HttpInterceptorFn = (req, next) => {
const client = req.headers.get('X-Client');
console.log(`-> ${req.method} ${req.urlWithParams} (X-Client: ${client})`);
return next(req).pipe(
tap((event) => {
if (event.type === HttpEventType.Response) {
console.log(`<- ${event.status} ${req.urlWithParams}`);
}
}),
);
};
and switch them on in app.config.ts:
// src/app/app.config.ts
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { clientHeaderInterceptor, loggingInterceptor } from './interceptors';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideHttpClient(withInterceptors([clientHeaderInterceptor, loggingInterceptor])),
],
};
app.ts and book-api.ts stay as they were. Click Load books. The page shows 3 books, as before, and the console shows:
-> GET /books.json (X-Client: reading-list)
<- 200 /books.json
Here’s what each piece does.
- An interceptor has the type
HttpInterceptorFn. It’s a plain function that gets two things:req, the request, andnext, a function that passes a request on to whatever comes after this interceptor. It returns whatnextreturns: an Observable of what comes back. - A request can’t be changed. Its fields are read-only. To change one, you make a changed copy with
req.clone(...).setHeadersadds headers to the copy. Then you pass the copy tonext. loggingInterceptorlogs on the way out, then callsnext(req). To see the response on its way back, it adds.pipe(tap(...)).pipeandtapare RxJS:tapruns a function on each value that comes through, without changing it. Part 20 has more.- An interceptor sees more than the final response.
HttpClientalso sends small events through the chain, such as one when the request is sent.event.type === HttpEventType.Responsepicks out the response. Inside thatif, TypeScript knowseventis anHttpResponse, soevent.statusis allowed. provideHttpClient(withInterceptors([...]))inapp.config.tsturns them on for the whole app. The list order is the order requests go through them.
The log line shows that the header arrived. loggingInterceptor comes second, so it sees the copy that clientHeaderInterceptor made.
A request through the chain
This animation follows one list() call through both interceptors and back. Solid black arrows are the request going out. Solid blue arrows are the response coming back.
A request goes through the interceptors in list order, and the response comes back in reverse.
Here are those steps in words, in case the animation doesn’t play for you:
api.list()returns an Observable that describes a GET for/books.json. Nothing has been sent.subscribe()starts it. The request goes to the first interceptor in the list,clientHeaderInterceptor. It makes a copy with anX-Clientheader and passes the copy tonext.nexthands the copy tologgingInterceptor. It logs the request, header and all, and callsnext(req).- There are no more interceptors, so
nexthands the request to the backend, the part ofHttpClientthat really sends it, using the browser’sfetch. The server answers 200 with the JSON. - The response travels back the way it came: through
loggingInterceptor, whosetaplogs<- 200, then throughclientHeaderInterceptor, which passes it on unchanged, to the function you gavesubscribe().
Order matters
Swap the two in the list:
// src/app/app.config.ts
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { clientHeaderInterceptor, loggingInterceptor } from './interceptors';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideHttpClient(withInterceptors([loggingInterceptor, clientHeaderInterceptor])),
],
};
Click Load books, and the console shows:
-> GET /books.json (X-Client: null)
<- 200 /books.json
The header still reaches the server, because clientHeaderInterceptor still adds it. But the logger now runs first, before the header exists, so it reports null. On the way back, the order is reversed: the last interceptor in the list sees the response first. Put an interceptor that changes requests before one that needs to see the change.
In older code
Before functional interceptors, an interceptor was a class with an intercept(req, next) method, registered with { provide: HTTP_INTERCEPTORS, useClass: ..., multi: true } and switched on with withInterceptorsFromDi(). Before Angular 21, every app had to add provideHttpClient(). Older apps also turned on HTTP with HttpClientModule in an NgModule, which is deprecated, or with provideHttpClient(withFetch()). In Angular 22, withFetch() is deprecated too: HttpClient already uses the browser’s fetch by default. Write new interceptors as functions.
Query params
Many APIs take options in the address, after a ?: /books?author=Dahl&limit=2. Those are query params. Don’t glue them onto the string yourself. Pass them as params, and HttpClient adds them and encodes any spaces or special characters.
First, put the interceptors back in their first order, header first:
// src/app/app.config.ts
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { clientHeaderInterceptor, loggingInterceptor } from './interceptors';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideHttpClient(withInterceptors([clientHeaderInterceptor, loggingInterceptor])),
],
};
Then add a byAuthor method to BookApi, and call it from App:
// src/app/book-api.ts
import { HttpClient } from '@angular/common/http';
import { Service, inject } from '@angular/core';
import { Observable } from 'rxjs';
export interface Book {
id: number;
title: string;
author: string;
}
@Service()
export class BookApi {
private readonly http = inject(HttpClient);
list(): Observable<Book[]> {
return this.http.get<Book[]>('/books.json');
}
byAuthor(author: string, limit: number): Observable<Book[]> {
return this.http.get<Book[]>('/books.json', { params: { author, limit } });
}
}
// src/app/app.ts
import { Component, inject, signal } from '@angular/core';
import { Book, BookApi } from './book-api';
@Component({
selector: 'app-root',
template: `
<button (click)="load()">Books by Roald Dahl</button>
<p>{{ books().length }} books</p>
`,
})
export class App {
private readonly api = inject(BookApi);
protected readonly books = signal<Book[]>([]);
protected load() {
this.api.byAuthor('Roald Dahl', 2).subscribe((books) => this.books.set(books));
}
}
Click Books by Roald Dahl. The console shows:
-> GET /books.json?author=Roald%20Dahl&limit=2 (X-Client: reading-list)
<- 200 /books.json?author=Roald%20Dahl&limit=2
{ author, limit } is short for { author: author, limit: limit }. A param’s value can be a string, a number or a boolean, or a list of those. Our test server is just a folder of files, so it ignores the params and sends all three books. A real API would read them and filter.
params also takes an HttpParams object, which you’ll meet in code that builds params step by step: new HttpParams().set('author', 'Roald Dahl').set('limit', 2). Like a request, an HttpParams can’t be changed. set returns a new one. Exercise 1 is about that.
Errors: when the request fails
Servers say no. A file is missing, a user isn’t logged in, the server crashes. When the answer has an error status, like 404 or 500, HttpClient doesn’t call your next function. It calls error with an HttpErrorResponse.
Here’s a component that asks for a file that doesn’t exist. It keeps the state in three signals, like the store in Part 15:
// src/app/app.ts
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Component, inject, signal } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<button (click)="load()">Load</button>
@if (loading()) {
<p>Loading...</p>
} @else if (error()) {
<p>Couldn't load the books: {{ error() }}</p>
} @else {
<p>{{ count() }} books</p>
}
`,
})
export class App {
private readonly http = inject(HttpClient);
protected readonly count = signal(0);
protected readonly loading = signal(false);
protected readonly error = signal('');
protected load() {
this.loading.set(true);
this.error.set('');
this.http.get<unknown[]>('/missing.json').subscribe({
next: (books) => {
this.count.set(books.length);
this.loading.set(false);
},
error: (err: HttpErrorResponse) => {
this.error.set(`status ${err.status}`);
this.loading.set(false);
},
});
}
}
Click Load. The page shows:
Load
Couldn't load the books: status 404
The console’s log has only the outgoing line from our logging interceptor:
-> GET /missing.json (X-Client: reading-list)
The browser console also shows a red line, which the browser writes for any failed request:
Failed to load resource: the server responded with a status of 404 (Not Found)
Some notes:
subscribehere gets an object withnextanderror. Only one of them runs.HttpErrorResponsecomes from@angular/common/http.statusis the number the server sent. There’s also astatusText, but it’s deprecated: over HTTP/2 the server sends no text, so Angular fills inUnknown Error. Usestatus. AnHttpErrorResponsealso haserror, the body the server sent with the failure (often a JSON message from a real API), andmessage, a sentence such asHttp failure response forthe full address, then the status. The address includes the server’s name and port, so it’s better for logs than for the screen.- We set
loadingback tofalsein both branches. Forget it inerror, and the page says “Loading…” forever. - The interceptors from before still log the request, since they’re in
app.config.ts. Their<-line doesn’t appear, because noHttpResponsecame back. The failure travels back throughpipeas an error, whichtap‘s function doesn’t see.
If no answer arrives at all (you’re offline, the server is down, or the browser blocked the request), status is 0. Check status === 0 if you want to say “couldn’t reach the server” instead of showing a server message.
Worked example: POST through an interceptor that plays the server
get reads. post sends data to be saved. Its second argument is the body: an object that HttpClient turns into JSON. The server usually answers with the saved item, and post<Book> says what that looks like.
We have a problem, though. Our test server only serves files. It can’t save a book. So we’ll let an interceptor play the server. An interceptor doesn’t have to call next: it can answer the request itself. That’s a real technique for building a page before the API exists, and for demos like this one. (Tests use a different tool, HttpTestingController, in Part 25.)
Add a third interceptor to interceptors.ts:
// src/app/interceptors.ts
import { HttpEventType, HttpInterceptorFn, HttpResponse } from '@angular/common/http';
import { of, tap } from 'rxjs';
export const clientHeaderInterceptor: HttpInterceptorFn = (req, next) => {
const withHeader = req.clone({ setHeaders: { 'X-Client': 'reading-list' } });
return next(withHeader);
};
export const loggingInterceptor: HttpInterceptorFn = (req, next) => {
const client = req.headers.get('X-Client');
console.log(`-> ${req.method} ${req.urlWithParams} (X-Client: ${client})`);
return next(req).pipe(
tap((event) => {
if (event.type === HttpEventType.Response) {
console.log(`<- ${event.status} ${req.urlWithParams}`);
}
}),
);
};
let nextId = 4;
export const fakeBackendInterceptor: HttpInterceptorFn = (req, next) => {
if (req.method === 'POST' && req.url === '/api/books') {
const input = req.body as { title: string; author: string };
const saved = { id: nextId++, ...input };
return of(new HttpResponse({ status: 201, body: saved }));
}
return next(req);
};
// src/app/app.config.ts
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import {
clientHeaderInterceptor,
fakeBackendInterceptor,
loggingInterceptor,
} from './interceptors';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideHttpClient(
withInterceptors([clientHeaderInterceptor, loggingInterceptor, fakeBackendInterceptor]),
),
],
};
Then give BookApi an add method, and the component a form:
// src/app/book-api.ts
import { HttpClient } from '@angular/common/http';
import { Service, inject } from '@angular/core';
import { Observable } from 'rxjs';
export interface Book {
id: number;
title: string;
author: string;
}
@Service()
export class BookApi {
private readonly http = inject(HttpClient);
list(): Observable<Book[]> {
return this.http.get<Book[]>('/books.json');
}
add(title: string, author: string): Observable<Book> {
return this.http.post<Book>('/api/books', { title, author });
}
}
// src/app/app.ts
import { Component, inject, signal } from '@angular/core';
import { Book, BookApi } from './book-api';
@Component({
selector: 'app-root',
template: `
<button (click)="load()">Load books</button>
<input #title aria-label="Title" />
<button (click)="add(title.value)">Add</button>
<ul>
@for (book of books(); track book.id) {
<li>{{ book.id }}. {{ book.title }}</li>
}
</ul>
`,
})
export class App {
private readonly api = inject(BookApi);
protected readonly books = signal<Book[]>([]);
protected load() {
this.api.list().subscribe((books) => this.books.set(books));
}
protected add(title: string) {
this.api.add(title, 'Unknown').subscribe((saved) => {
this.books.update((list) => [...list, saved]);
});
}
}
#title is a template reference variable from Part 2: title.value is what’s in the box. Click Load books, type Holes into the box and click Add. The page shows:
Load booksAdd
1. A Wizard of Earthsea
2. The Hobbit
3. Matilda
4. Holes
and the console shows:
-> GET /books.json (X-Client: reading-list)
<- 200 /books.json
-> POST /api/books (X-Client: reading-list)
<- 201 /api/books
Follow the POST. clientHeaderInterceptor adds the header. loggingInterceptor logs it and calls next. fakeBackendInterceptor sees a POST to /api/books, so it doesn’t call next. It builds an HttpResponse with status 201 (“Created”) and the saved book as the body. of(...) is RxJS: an Observable that gives that one value and finishes. The response travels back through the logger, which logs <- 201, and reaches our subscribe, which adds the book to the list with a new array, as in Part 3.
The GET to /books.json goes past the fake: its if doesn’t match, so it calls next(req), and the request goes to the real server. When your real API is ready, remove fakeBackendInterceptor from the list. BookApi and the component don’t change.
Worked example: forgetting the type
Here’s BookApi from the last example with the <Book[]> left off get:
// src/app/book-api.ts
import { HttpClient } from '@angular/common/http';
import { Service, inject } from '@angular/core';
import { Observable } from 'rxjs';
export interface Book {
id: number;
title: string;
author: string;
}
@Service()
export class BookApi {
private readonly http = inject(HttpClient);
list(): Observable<Book[]> {
return this.http.get('/books.json');
}
add(title: string, author: string): Observable<Book> {
return this.http.post<Book>('/api/books', { title, author });
}
}
The build stops:
✘ [ERROR] TS2322: Type 'Observable<Object>' is not assignable to type 'Observable<Book[]>'.
...
The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
Type 'Object' is missing the following properties from type 'Book[]': length, pop, push, concat, and 29 more. [plugin angular-compiler]
src/app/book-api.ts:17:4:
17 │ return this.http.get('/books.json');
╵ ~~~~~~
Read it piece by piece:
TS2322is TypeScript’s “this value doesn’t fit where you put it” error. The first line says what didn’t fit: anObservable<Object>where the method promised anObservable<Book[]>.- The
...stands for several lines we left out. TypeScript explains, layer by layer, why the two types don’t match. You can usually skip to the last lines. - The last lines say it plainly. Without a type,
getreturns the body asObject, a type that “is assignable to very few other types”. AnObjectisn’t known to havelength,pushand the rest of what a list has. src/app/book-api.ts:17:4is the file, line and column, and the~~~~~~marks thereturn.
So the error isn’t really about Observables. It’s the response type. get without a type gives you Object, and Object doesn’t fit anywhere useful. TypeScript’s hint about any would make the error go away, and switch off checking for everything that uses the books. Don’t take it.
Put <Book[]> back on get, and it builds again.
Best practices
- Put requests in a service that returns Observables. Components call
api.list(), nothttp.get('/books.json'). Addresses and headers then live in one place, instead of being copied into every component. - Always give
getandposta response type.get<Book[]>lets TypeScript check everything you do with the answer. Without it, you getObjectand casts everywhere. - Use
paramsfor query strings. It encodes values for you. It replaces building'?author=' + nameby hand, which breaks on spaces and&. - Write interceptors as functions, and keep each one to one job. A header, logging, a fake backend: each is short and easy to reorder. They replace class-based interceptors and code copied into every request.
- Handle
errorwherever yousubscribe. Show the user something, and reset any loading flag. An unhandled HTTP error leaves the page stuck and anERRORin the console.
Tips and traps
- Forgetting to subscribe. No request appears in the Network tab, and no error is shown. Call
subscribe()(or, from Part 19 on, usehttpResource, which subscribes for you). - Subscribing twice. Two
subscribe()calls on one Observable send two requests. It shows up as doubled lines in the Network tab. Subscribe once and keep the result in a signal. - Passing the original request to
next.req.clone(...)returns a copy and leavesreqalone. If you writereq.clone(...)and thennext(req), the header never leaves. Pass the copy. - Interceptors in the wrong order. A logger listed before the interceptor that adds a header logs
nullfor it. Requests go through the list from first to last. - Trusting the response type.
get<Book[]>doesn’t check the data. A renamed field on the server shows up as blank text, not an error. Look at the real response in the Network tab. - A stuck “Loading…”. You set
loadingtotrueand only reset it innext. When the request fails, nothing resets it. Reset it inerrortoo.
An HttpClient request is a plan until you subscribe, and every interceptor sees it on the way out and the way back.
Exercises
Exercise 1. This byAuthor method should send ?author=Roald%20Dahl, but the logging interceptor shows plain /books.json. Why? Fix it. (The interceptors and app.config.ts are the ones from the POST example.)
// src/app/book-api.ts
import { HttpClient, HttpParams } from '@angular/common/http';
import { Service, inject } from '@angular/core';
import { Observable } from 'rxjs';
export interface Book {
id: number;
title: string;
author: string;
}
@Service()
export class BookApi {
private readonly http = inject(HttpClient);
list(): Observable<Book[]> {
return this.http.get<Book[]>('/books.json');
}
byAuthor(author: string): Observable<Book[]> {
const params = new HttpParams();
params.set('author', author);
return this.http.get<Book[]>('/books.json', { params });
}
}
// src/app/app.ts
import { Component, inject, signal } from '@angular/core';
import { Book, BookApi } from './book-api';
@Component({
selector: 'app-root',
template: `
<button (click)="load()">Roald Dahl</button>
<p>{{ books().length }} books</p>
`,
})
export class App {
private readonly api = inject(BookApi);
protected readonly books = signal<Book[]>([]);
protected load() {
this.api.byAuthor('Roald Dahl').subscribe((books) => this.books.set(books));
}
}
-> GET /books.json (X-Client: reading-list)
<- 200 /books.json
Exercise 2. With the same interceptors and BookApi, how many -> lines does this log when you click Load? Guess before you run it.
// src/app/app.ts
import { Component, inject, signal } from '@angular/core';
import { Book, BookApi } from './book-api';
@Component({
selector: 'app-root',
template: `
<button (click)="load()">Load</button>
<p>{{ count() }} of {{ books().length }}</p>
`,
})
export class App {
private readonly api = inject(BookApi);
protected readonly books = signal<Book[]>([]);
protected readonly count = signal(0);
protected load() {
const books$ = this.api.list();
books$.subscribe((books) => this.books.set(books));
books$.subscribe((books) => this.count.set(books.length));
}
}
The $ at the end of books$ is a common naming habit for a variable that holds an Observable. It doesn’t do anything.
Exercise 3. The server team released a new version of the book list. Our stand-in for it is public/books-v2.json. Since then, the list shows each author but no titles. The build is clean, and there’s no error in the console. What happened?
Here’s the new file and the page:
[
{ "id": 1, "name": "A Wizard of Earthsea", "author": "Ursula K. Le Guin" },
{ "id": 2, "name": "The Hobbit", "author": "J. R. R. Tolkien" }
]
// src/app/app.ts
import { HttpClient } from '@angular/common/http';
import { Component, inject, signal } from '@angular/core';
interface Book {
id: number;
title: string;
author: string;
}
@Component({
selector: 'app-root',
template: `
<button (click)="load()">Load</button>
<ul>
@for (book of books(); track book.id) {
<li>{{ book.title }} by {{ book.author }}</li>
}
</ul>
`,
})
export class App {
private readonly http = inject(HttpClient);
protected readonly books = signal<Book[]>([]);
protected load() {
this.http.get<Book[]>('/books-v2.json').subscribe((books) => this.books.set(books));
}
}
Click Load. The page shows:
Load
by Ursula K. Le Guin
by J. R. R. Tolkien
Answers
1. HttpParams can’t be changed. params.set(...) returns a new HttpParams with the author in it, and the code throws that away. params is still empty. Keep what set returns:
// src/app/book-api.ts
import { HttpClient, HttpParams } from '@angular/common/http';
import { Service, inject } from '@angular/core';
import { Observable } from 'rxjs';
export interface Book {
id: number;
title: string;
author: string;
}
@Service()
export class BookApi {
private readonly http = inject(HttpClient);
list(): Observable<Book[]> {
return this.http.get<Book[]>('/books.json');
}
byAuthor(author: string): Observable<Book[]> {
const params = new HttpParams().set('author', author);
return this.http.get<Book[]>('/books.json', { params });
}
}
// src/app/app.ts
import { Component, inject, signal } from '@angular/core';
import { Book, BookApi } from './book-api';
@Component({
selector: 'app-root',
template: `
<button (click)="load()">Roald Dahl</button>
<p>{{ books().length }} books</p>
`,
})
export class App {
private readonly api = inject(BookApi);
protected readonly books = signal<Book[]>([]);
protected load() {
this.api.byAuthor('Roald Dahl').subscribe((books) => this.books.set(books));
}
}
Click Roald Dahl. The console shows:
-> GET /books.json?author=Roald%20Dahl (X-Client: reading-list)
<- 200 /books.json?author=Roald%20Dahl
The space in the name is sent as %20, the way addresses encode a space. Passing { params: { author } } would do the same with less code.
2. Two. books$ is a cold Observable, and each subscribe() starts its own request:
// src/app/app.ts
import { Component, inject, signal } from '@angular/core';
import { Book, BookApi } from './book-api';
@Component({
selector: 'app-root',
template: `
<button (click)="load()">Load</button>
<p>{{ count() }} of {{ books().length }}</p>
`,
})
export class App {
private readonly api = inject(BookApi);
protected readonly books = signal<Book[]>([]);
protected readonly count = signal(0);
protected load() {
const books$ = this.api.list();
books$.subscribe((books) => this.books.set(books));
books$.subscribe((books) => this.count.set(books.length));
}
}
Click Load. The console shows:
-> GET /books.json (X-Client: reading-list)
-> GET /books.json (X-Client: reading-list)
<- 200 /books.json
<- 200 /books.json
and the page shows:
Load
3 of 3
Both numbers are right, but it cost two requests. Subscribe once and set both signals in one function, or better, keep one signal and use computed for the count, as in Part 3.
3. The server renamed title to name. The interface still says title. get<Book[]> is only a promise to TypeScript, so nothing checked the data, and book.title is undefined for every book. Angular shows undefined as empty text. Change the interface and the template to match what the server now sends:
// src/app/app.ts
import { HttpClient } from '@angular/common/http';
import { Component, inject, signal } from '@angular/core';
interface Book {
id: number;
name: string;
author: string;
}
@Component({
selector: 'app-root',
template: `
<button (click)="load()">Load</button>
<ul>
@for (book of books(); track book.id) {
<li>{{ book.name }} by {{ book.author }}</li>
}
</ul>
`,
})
export class App {
private readonly http = inject(HttpClient);
protected readonly books = signal<Book[]>([]);
protected load() {
this.http.get<Book[]>('/books-v2.json').subscribe((books) => this.books.set(books));
}
}
Click Load. The page shows:
Load
A Wizard of Earthsea by Ursula K. Le Guin
The Hobbit by J. R. R. Tolkien
What’s next
In this part, every component had to call subscribe, copy the result into a signal, and track loading and errors by hand. In Part 19, resource and httpResource do all of it for you, with loading and error states built in, and that’s how most component code in this series will load data from here on.