Angular · Lesson 5
HTTP & RxJS in Angular
HttpClient with typed responses, functional interceptors (auth headers, retries, error mapping, a single-flight 401 refresh), the async pipe, takeUntilDestroyed, toSignal and toObservable, httpResource, and error handling patterns that keep the UI honest.
In short
get<T>is a cast; calls are cold, lazy, and emit once- Interceptors are functions; their order is a design decision
- Retry only idempotent requests and transient errors
- Prefer the
asyncpipe,toSignalandhttpResource - Manual subscriptions end with
takeUntilDestroyed()
Almost every Angular screen loads something from an API, and almost every Angular bug report has an HTTP call in
it somewhere: a spinner that never stops, a request sent twice, a token that expired mid-session, a list that shows
the previous customer's orders. This topic is about the seam between Angular and RxJS: HttpClient, interceptors,
and getting async data into templates without leaks.
It assumes you know Observables and the main operators. The RxJS & Observables topic in the TypeScript track
covers those in depth (flattening operators, catchError placement, sharing, marble tests). Snippets that only
use RxJS have a ▶ Try button. Snippets that need Angular itself are shown without one.
Setting up HttpClient
You configure HttpClient once, in app.config.ts. That's also where interceptors are registered:
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { authInterceptor, errorInterceptor, retryInterceptor } from './core/http';
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient(withInterceptors([errorInterceptor, retryInterceptor, authInterceptor]))],
};
Then any service can inject(HttpClient). Older code uses HttpClientModule and class-based interceptors
registered with the HTTP_INTERCEPTORS multi-provider. Those still work through withInterceptorsFromDi(), but new
code uses functional interceptors.
Typed requests
The usual shape is a small API service per feature that returns Observables:
import { HttpClient, HttpResponse } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { Observable } from 'rxjs';
export interface Order {
id: string;
total: number;
placedAt: string; // JSON has no dates: this is an ISO string, not a Date
}
@Injectable({ providedIn: 'root' })
export class OrderApi {
private readonly http = inject(HttpClient);
list(page: number): Observable<Order[]> {
return this.http.get<Order[]>('/api/orders', { params: { page, pageSize: 20 } });
}
create(draft: Omit<Order, 'id' | 'placedAt'>): Observable<Order> {
return this.http.post<Order>('/api/orders', draft);
}
// The whole response (status, headers), not just the body:
getWithHeaders(id: string): Observable<HttpResponse<Order>> {
return this.http.get<Order>(`/api/orders/${id}`, { observe: 'response' });
}
}
Four things to know about every call:
get<Order>is a promise you make to the compiler, not a check. Angular parses the JSON and casts it. If the API sendstotalAmountinstead oftotal, nothing fails until a template showsundefined. Dates arrive as strings. For APIs you don't control, validate at the edge (a type guard or a schema library like zod). For your own ASP.NET Core API, generate the client and its types from the OpenAPI document (NSwag, openapi-generator, Kiota), so the types follow the C# models.- Calls are cold and lazy. Nothing is sent until you subscribe. Every subscription sends a new request.
- A call emits once and completes, or errors with an
HttpErrorResponse. HttpParams,HttpHeadersandHttpRequestare immutable.params.set('page', '2')returns a new object and leavesparamsunchanged. Passing a plain object ({ params: { page } }) avoids the trap.
Here is the lazy, per-subscription behaviour with a stand-in for http.get:
import { defer, delay, of } from 'rxjs';
let sent = 0;
const getOrders = () =>
defer(() => {
sent++;
console.log(`request ${sent} sent`);
return of(['A-1', 'A-2']).pipe(delay(10));
});
const orders$ = getOrders();
console.log('Observable created, requests sent:', sent);
orders$.subscribe((orders) => console.log('first subscriber got', orders));
orders$.subscribe((orders) => console.log('second subscriber got', orders));
Two | async pipes on the same http.get(...) are two subscriptions, so two requests. Subscribe once
(@let orders = orders$ | async;), share it (shareReplay), or put it in a signal.
Functional interceptors
An interceptor sees every request on the way out and every response (or error) on the way back. It's a function:
// The type, from @angular/common/http (not runnable here)
type HttpInterceptorFn = (req: HttpRequest<unknown>, next: HttpHandlerFn) => Observable<HttpEvent<unknown>>;
It can change the request (req.clone(...)), answer by itself (a cache), or pipe operators onto next(req) to work on
the response. Interceptors run in an injection context, so inject() works inside them:
import { HttpContextToken, HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthStore } from './auth.store';
import { API_BASE_URL } from './tokens';
export const SKIP_AUTH = new HttpContextToken<boolean>(() => false);
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = inject(AuthStore).accessToken();
const isOurApi = req.url.startsWith(`${inject(API_BASE_URL)}/`);
if (!token || !isOurApi || req.context.get(SKIP_AUTH)) return next(req);
return next(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }));
};
// A caller opts out per request:
// http.post('/api/auth/refresh', body, { context: new HttpContext().set(SKIP_AUTH, true) });
HttpContextToken is how you pass per-request options to interceptors ("don't retry this", "no auth", "cache for 60
seconds") without inventing headers.
The onion. withInterceptors([a, b, c]) runs a, then b, then c on the way out, and the response comes back
through c, then b, then a. Code before next(req) runs on the way in, operators after it run on the way out:
import { Observable, of, tap } from 'rxjs';
type Handler = (url: string) => Observable<string>;
type Interceptor = (url: string, next: Handler) => Observable<string>;
const logging =
(name: string): Interceptor =>
(url, next) => {
console.log(`${name}: request ${url}`);
return next(url).pipe(tap((response) => console.log(`${name}: response ${response}`)));
};
const backend: Handler = (url) => of(`200 for ${url}`);
// What withInterceptors([a, b]) builds:
const handler: Handler = (url) => logging('a')(url, (u) => logging('b')(u, backend));
handler('/api/orders').subscribe();
So the order you list them in is a design decision:
| Position | Interceptor | Why there |
|---|---|---|
| outermost | error mapping | sees the final error, after retries gave up |
| retry | everything after it runs again for each retry | |
| auth (and 401 refresh) | each retry picks up the current token | |
| innermost | logging, timing | measures the real round trip |
Four interceptors every app ends up writing
Auth header. Add the bearer token, but only for your API. Check the URL carefully: startsWith('https://api.example.com')
also matches https://api.example.com.evil.example. (Exercise 3.)
Retry. Retry only what's safe and useful: idempotent methods (GET, PUT, DELETE) and transient failures
(0, 408, 429, 502, 503, 504), with exponential backoff, respecting Retry-After. Never blindly retry a POST:
it may have worked the first time. (Exercise 4.)
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { retry, throwError, timer } from 'rxjs';
const IDEMPOTENT = new Set(['GET', 'PUT', 'DELETE']);
const TRANSIENT = new Set([0, 408, 429, 502, 503, 504]);
export const retryInterceptor: HttpInterceptorFn = (req, next) =>
!IDEMPOTENT.has(req.method)
? next(req)
: next(req).pipe(
retry({
count: 3,
delay: (error, attempt) =>
error instanceof HttpErrorResponse && TRANSIENT.has(error.status) ? timer(300 * 2 ** (attempt - 1)) : throwError(() => error),
}),
);
Error mapping. Turn HttpErrorResponse into a small union your UI understands, in one place. Status 0 means no
response at all: offline, DNS, or a CORS rejection. ASP.NET Core sends validation failures as
ValidationProblemDetails ({ errors: { Email: ['...'] } }), which you can map onto form fields. (Exercise 1.)
401 refresh. When the access token expires, get a new one and resend, with one refresh shared by every request
that failed at the same time. (Exercise 7.) If you use an OIDC client library (such as angular-oauth2-oidc
or your identity provider's Angular SDK), it usually refreshes tokens for you and you rarely write this yourself.
Getting data into the template
There are three ways, and modern code uses all of them.
The async pipe subscribes when the view is created, marks an OnPush view for check on each value, and
unsubscribes when the view is destroyed or the Observable changes. It returns null until the first value:
@if (order$ | async; as order) {
<app-order-details [order]="order" />
} @else {
<app-spinner />
}
toSignal turns an Observable into a signal (stable since Angular 20, developer preview in 19). It subscribes
immediately (not on first read) and unsubscribes when the component is destroyed:
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { OrderApi } from './order-api';
@Component({
selector: 'app-orders',
template: `@for (order of orders(); track order.id) { <app-order-row [order]="order" /> }`,
})
export class Orders {
private readonly api = inject(OrderApi);
readonly orders = toSignal(this.api.list(1), { initialValue: [] }); // Signal<Order[]>
}
- Without
initialValuethe type isSignal<T | undefined>, because there's a moment before the first value. requireSync: truedropsundefinedfrom the type for sources that emit synchronously (aBehaviorSubject, astartWith), and throws if they don't.- If the Observable errors, reading the signal throws. Handle errors in the stream before converting.
httpResource and resource are signal-based loaders. They were experimental in Angular 19, 20 and 21, and are
stable since Angular 22. You give them a function of signals; they load whenever those signals change, cancel the
previous load, and expose value(), isLoading(), error(), status() and hasValue():
import { httpResource } from '@angular/common/http';
import { Component, input } from '@angular/core';
import { Order } from './order-api';
@Component({
selector: 'app-order-page',
template: `
@if (order.hasValue()) {
<app-order-details [order]="order.value()" />
} @else if (order.error()) {
<p>Could not load the order.</p>
} @else if (order.isLoading()) {
<app-spinner />
}
`,
})
export class OrderPage {
readonly id = input.required<string>(); // bound from the route
readonly order = httpResource<Order>(() => `/api/orders/${this.id()}`); // reloads when id() changes
}
resource({ params, loader }) does the same with any promise-returning loader (it gets an abortSignal), and
rxResource({ params, stream }) with an Observable. (Angular 19 called these options request and loader, so
older code and blog posts use those names.) Returning undefined from params (or from httpResource's
function) means "nothing to load yet", and the status is 'idle'. These are for reading. Saves, deletes and
other commands stay as HttpClient calls you subscribe to (or firstValueFrom and await).
async pipe | toSignal | httpResource | |
|---|---|---|---|
| subscribes | when the view renders | when the field is created | when its signals have a value |
| before the first value | null | undefined or initialValue | undefined, status 'loading' |
| errors | rethrown to ErrorHandler | thrown when the signal is read | error() and status 'error' |
| reloads when inputs change | you build it (switchMap) | you build it (switchMap) | built in, cancels the old request |
Signals into RxJS: toObservable
When a signal drives something time-based (debounce, cancellation), go the other way with toObservable:
import { Component, inject, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs';
import { ProductApi } from './product-api';
@Component({ selector: 'app-search', template: `<input [value]="query()" (input)="query.set($any($event.target).value)" />` })
export class Search {
private readonly api = inject(ProductApi);
readonly query = signal('');
readonly results = toSignal(
toObservable(this.query).pipe(debounceTime(300), distinctUntilChanged(), switchMap((q) => this.api.search(q))),
{ initialValue: [] },
);
}
toObservable watches the signal with an effect, so it's asynchronous. Setting the signal three times in a row emits
only the last value, a little later. That's fine for user input, and a surprise if you expect one emission per set.
Subscriptions and cleanup
Prefer the async pipe, toSignal and resources: they clean up for you. When you do subscribe yourself (to start
side effects: websocket updates, a store), end the subscription with the component:
import { Component, DestroyRef, inject, OnInit } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { OrderEvents } from './order-events';
@Component({ selector: 'app-live-orders', template: '' })
export class LiveOrders implements OnInit {
private readonly events = inject(OrderEvents);
private readonly destroyRef = inject(DestroyRef);
constructor() {
this.events.updates$.pipe(takeUntilDestroyed()).subscribe((u) => this.apply(u)); // injection context: no argument needed
}
ngOnInit() {
this.events.alerts$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((a) => this.show(a)); // not an injection context: pass the ref
}
private apply(update: unknown) {}
private show(alert: unknown) {}
}
- Without an argument,
takeUntilDestroyed()must run in an injection context (constructor, field initializer). Elsewhere it throws, so pass aDestroyRef. - Put it last in the pipe. An operator after it can keep inner subscriptions alive. Here destroy happens at 25 ms:
import { interval, of, Subject, switchMap, takeUntil } from 'rxjs';
function run(label: string, order: 'leaky' | 'safe') {
const destroy$ = new Subject<void>(); // stands in for the component's DestroyRef
let ticks = 0;
const source$ = of('start');
const subscription = (
order === 'leaky'
? source$.pipe(takeUntil(destroy$), switchMap(() => interval(10)))
: source$.pipe(switchMap(() => interval(10)), takeUntil(destroy$))
).subscribe(() => ticks++);
setTimeout(() => destroy$.next(), 25);
setTimeout(() => {
console.log(`${label}: ${ticks > 3 ? 'still ticking after destroy' : 'stopped at destroy'}`);
subscription.unsubscribe();
}, 80);
}
run('takeUntil first', 'leaky');
run('takeUntil last ', 'safe');
- HTTP calls complete by themselves, so they don't leak. Unsubscribing still cancels a request nobody needs (the
user left the page), which
switchMap, theasyncpipe andtoSignaldo for you.
Error handling patterns
Decide where each error is handled.
- Interceptor: map to
AppError, retry transient failures, refresh tokens. Cross-cutting, written once. - Service or store: turn errors into state the UI can show (
status: 'error'), or rethrow for the caller. - Component: shows the state. It shouldn't parse status codes.
ErrorHandler: the global last resort for unexpected errors (log to your monitoring service, show a generic toast).
Keep streams alive. An error ends the stream it travels through. In a search or a polling stream, catch inside the
switchMap so one failed request doesn't kill the feature (the RxJS topic shows this in detail).
Model loading, success and failure as one value, so the template can't show a spinner next to stale data:
import { catchError, map, Observable, of, startWith, switchMap, throwError, timer } from 'rxjs';
type ViewState<T> = { status: 'loading' } | { status: 'ok'; data: T } | { status: 'error'; message: string };
function toViewState<T>(request$: Observable<T>): Observable<ViewState<T>> {
return request$.pipe(
map((data): ViewState<T> => ({ status: 'ok', data })),
catchError((e: unknown) => of<ViewState<T>>({ status: 'error', message: e instanceof Error ? e.message : String(e) })),
startWith<ViewState<T>>({ status: 'loading' }),
);
}
const works$ = timer(10).pipe(map(() => ['A-1', 'A-2']));
const fails$ = timer(10).pipe(switchMap(() => throwError(() => new Error('503 Service Unavailable'))));
toViewState(works$).subscribe((state) => console.log('works:', JSON.stringify(state)));
toViewState(fails$).subscribe((state) => console.log('fails:', JSON.stringify(state)));
Don't swallow errors. catchError(() => EMPTY) turns a failure into "completed with no value". The template shows
nothing and nobody knows why. firstValueFrom on it rejects with an EmptyError, and rxResource reports that the
stream completed without a value. Replace the error with a value that says what happened, or let it through.
Common mistakes
- Nested subscribes (
route.params.subscribe(p => http.get(...).subscribe(...))): no cancellation, races between responses, no cleanup. UseswitchMap. - Calling a method that returns an Observable from the template (
getOrders() | async): a new request on every change detection pass. Store the Observable (or signal) in a field. - Subscribing in a service and copying the result into a field: errors vanish and callers can't cancel. Return the Observable, or keep state in signals and expose it read-only.
- Trusting
get<T>: it's a cast. Dates are strings, and a renamed field isundefinedat runtime. params.set(...)without using the result:HttpParamsis immutable.- Retrying non-idempotent requests, or retrying
4xxerrors that will fail the same way again. - Sending the token everywhere: check the URL in the auth interceptor.
takeUntilDestroyed()outside an injection context, or not last in the pipe.
How it looks in a real codebase
Side note
core/http/holds the interceptors and theprovideHttpClient(...)setup. Each feature has adata-accessservice (or a generated client) that returns Observables or resources, and nothing else in the feature knows URLs.- Components read signals:
toSignal(...),httpResource(...), or a store service that holds signals (see the Testing & architecture topic). - Behind an API gateway, expect
429(often withRetry-After) from rate-limit policies, and401from JWT validation when tokens expire: the retry and refresh interceptors earn their keep there. - Tests use
provideHttpClientTesting()andHttpTestingControllerto answer requests without a server (see the Testing & architecture topic).
The exercises
- Map HTTP errors to a typed AppError: status codes and ASP.NET Core
ValidationProblemDetailsto a discriminated union. - Build takeUntilDestroyed:
takeUntilwith aDestroyRefnotifier, registered per subscription and cleaned up. - A functional interceptor chain: the onion with
reduceRightanddefer, an auth interceptor and a logger. - A retry interceptor that knows when not to retry: idempotent methods, transient statuses, backoff and
Retry-After. - Rebuild the async pipe: subscriptions per source,
markForCheck, and why template method calls loop. - Build toSignal, overloads and all: eager subscribe,
initialValue,requireSync, errors on read. - Refresh an expired token, once, for everyone: a single-flight 401 refresh with
share,finalizeandswitchMap.
Practise this lesson
In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app