Handling Loading and Error States
An HTTP request is never just 'data' — at any moment it is loading, has succeeded with a value, or has failed with an error, and a well-built UI needs to represent all three states clearly rather than assuming the happy path. Skipping loading and error handling produces the classic bad experience: a blank screen while data is fetching, or a broken UI when a request fails silently. Angular doesn't prescribe one official pattern, but a common and robust approach is to model request state as a small discriminated union or a set of signals, and to render the UI conditionally from that state using the @if/@switch control-flow syntax.
Cricket analogy: A live match is never just 'a score' — it's mid-over, just took a wicket, or rain-delayed, and a broadcast graphic that only shows the final result while ignoring those states leaves viewers staring at a frozen scoreboard.
Modeling state with signals
A clean approach is to expose three signals from a service or component — data, loading, and error — and update them explicitly around the HTTP call: set loading to true before the request, then in the success and error paths set loading back to false and populate either data or error accordingly. This keeps every possible UI state explicit and inspectable, and pairs naturally with computed() signals for derived state like 'isEmpty' (loaded but zero results).
Cricket analogy: Exposing loading, data, and error signals is like a scoreboard operator explicitly flicking three separate lights — 'match in progress', 'result posted', 'washed out' — before and after each session, so an 'isEmpty' computed can flag a no-result match cleanly.
import { Injectable, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError, finalize, of } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class ProductStore {
private http = inject(HttpClient);
readonly data = signal<Product[]>([]);
readonly loading = signal(false);
readonly error = signal<string | null>(null);
load(): void {
this.loading.set(true);
this.error.set(null);
this.http.get<Product[]>('/api/products').pipe(
catchError(err => {
this.error.set('Could not load products. Please try again.');
return of<Product[]>([]);
}),
finalize(() => this.loading.set(false))
).subscribe(products => this.data.set(products));
}
}Rendering state in the template
With loading, error, and data exposed as signals, the template becomes a straightforward, exhaustive @if/@else-if chain (or a discriminated-union @switch) that always shows exactly one of: a spinner, an error message with a retry action, an empty state, or the actual content. This avoids the common bug of an old error message lingering on screen after a subsequent successful reload, because every branch is driven by current signal values rather than manually toggled flags that can fall out of sync.
Cricket analogy: With loading, error, and data as signals, the broadcast graphic becomes an exhaustive @if/@else-if chain showing exactly one of 'rain delay', 'no result — retry coverage', or 'live score', avoiding the classic bug of yesterday's washed-out banner lingering after play resumes.
@Component({
selector: 'app-product-list',
standalone: true,
template: `
@if (store.loading()) {
<app-spinner />
} @else if (store.error()) {
<p class="error">{{ store.error() }}</p>
<button (click)="store.load()">Retry</button>
} @else if (store.data().length === 0) {
<p>No products found.</p>
} @else {
@for (product of store.data(); track product.id) {
<li>{{ product.name }}</li>
}
}
`,
})
export class ProductListComponent {
store = inject(ProductStore);
ngOnInit() { this.store.load(); }
}A discriminated-union alternative
For state machines with more nuance, a single discriminated-union type — { status: 'loading' } | { status: 'success'; data: T } | { status: 'error'; message: string } — held in one signal can be more robust than three separate signals, because TypeScript can narrow the type in each template branch and it becomes structurally impossible to represent invalid combinations like 'loading' and 'error' being true simultaneously, which three independent booleans/signals can accidentally allow if updates aren't sequenced carefully.
Cricket analogy: A discriminated union like {status:'rain-delay'} | {status:'live', score} | {status:'abandoned', reason} held in one signal is more robust than three separate flags, because it becomes structurally impossible for the scoreboard to claim 'rain-delay' and 'live' simultaneously, unlike three independent booleans updated out of sequence.
The finalize() RxJS operator runs its callback exactly once when the source Observable completes or errors, regardless of which happened — making it the ideal place to reset a loading flag exactly once instead of duplicating that logic in both the success and catchError branches.
A subtle bug: if you set loading.set(true) but a subsequent request is triggered before the first resolves (e.g. rapid clicking a 'reload' button), and you're not using switchMap to cancel the stale request, an older response can arrive after a newer one and incorrectly flip loading back to false or overwrite fresher data — combine loading state with switchMap-based cancellation for anything user-triggerable.
- Model loading, success, and error explicitly rather than assuming an HTTP call always succeeds quickly.
- Signals for data/loading/error (or a single discriminated-union signal) make every UI state explicit and inspectable.
- finalize() is the right operator to reset a loading flag exactly once, whether the request succeeds or errors.
- @if/@else-if chains (or @switch) in templates should render exactly one state at a time, driven by current signal values.
- A discriminated union prevents structurally invalid combinations like simultaneous loading and error states.
- Combine switchMap with loading state for user-retriggerable requests to avoid stale responses corrupting current state.
Practice what you learned
1. Which RxJS operator guarantees a callback runs exactly once when an Observable completes or errors, regardless of outcome?
2. What is a key advantage of modeling request state as a single discriminated union instead of three separate booleans?
3. What common bug occurs when a UI doesn't clear a previous error state before a new successful load completes?
4. Why should catchError set a user-facing error signal rather than only console.error the failure?
5. Why pair switchMap with loading state for a user-retriggerable action like a 'reload' button?
Was this page helpful?
You May Also Like
HttpClient and Fetching Data
Learn how Angular's HttpClient issues typed, Observable-based HTTP requests, and how to provide it in a standalone application.
RxJS Operators for HTTP (map, switchMap, catchError)
Master the core RxJS operators — map, switchMap, catchError, and their flattening cousins — used to transform, chain, and recover from HTTP requests.
Introduction to Signals
Understand Angular Signals — the reactive primitive that wraps a value and notifies dependents on change, forming the foundation of Angular's modern change-detection model.
computed() and effect()
Learn how computed() derives memoized reactive values from signals, and how effect() runs side effects automatically whenever the signals it reads change.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebSockets Study Notes
Web Development · 30 topics
Web DevelopmentWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentSpring Boot Study Notes
Java · 30 topics
Web DevelopmentFlask Study Notes
Python · 30 topics
Web DevelopmentDjango Study Notes
Python · 30 topics