Sub topic 8
Displaying asynchronous data with the async pipe
This chapter assumes you know basic TypeScript, Angular components with template interpolation, and standalone components with an imports array. It also assumes you have met RxJS Observables and Promises at a basic level: you know that an Observable emits values over time and that you call subscribe to receive them.
Why the async pipe exists
Most real data arrives late. An HTTP request returns after some milliseconds, a router parameter changes when the user navigates, and a WebSocket pushes messages whenever the server sends them. Each of these is usually modeled as an Observable or a Promise.
A template cannot print an Observable directly. If you write {{ user$ }}, Angular shows [object Object]. The manual fix is to subscribe in the component, copy each value into a field, and unsubscribe when the component is destroyed. That is three pieces of code for every stream, and forgetting the last one causes memory leaks.
The async pipe does all three steps for you. It subscribes to the Observable or Promise, returns the latest emitted value, asks Angular to re-check the view when a new value arrives, and unsubscribes when the component is destroyed.
@if (user$ | async; as user) {
<p>{{ user.name }}</p>
}Here user$ is an Observable of a user object. The trailing $ is a naming convention for Observables, not syntax.
How it behaves internally
The pipe holds a subscription between change detection runs. Understanding its life cycle explains most of the surprises you will meet.
- On the first run, the pipe receives the source, subscribes, and returns
nullbecause no value has arrived yet. - When the source emits, the pipe stores the value and marks the view for check. Angular re-renders, and the pipe now returns the stored value.
- If the template passes a different Observable instance later, the pipe disposes of the old subscription and subscribes to the new one.
- When the component is destroyed, the pipe unsubscribes.
The diagram below shows the same sequence.
Two consequences follow from step 1. The pipe returns null before the first emission, so templates must handle null. For a Promise, the pipe also returns null until the Promise resolves.
Handling the initial null
Because the first value is null, an expression such as {{ (user$ | async).name }} throws an error at first render. Use one of these patterns instead.
Guard with @if and as
The @if block with as skips its content while the value is falsy, then renders it with the value bound to a local name.
@if (user$ | async; as user) {
<p>{{ user.name }}</p>
} @else {
<p>Loading…</p>
}The @else branch covers the time before the first emission. It also covers a case you may not intend: a falsy emitted value such as 0, '', or false also takes the @else branch. If the stream legitimately emits those values, test explicitly:
@let count = count$ | async;
@if (count !== null) {
<p>Items: {{ count }}</p>
} @else {
<p>Loading…</p>
}Use the safe navigation operator
When you only need one property, ?. avoids the error and prints nothing until the value arrives.
<p>{{ (user$ | async)?.name }}</p>Use the pipe with a fallback
The nullish coalescing operator ?? supplies a default for simple values.
<p>Total: {{ (total$ | async) ?? 0 }}</p>One subscription per pipe use
Every occurrence of | async creates its own subscription. This matters when the Observable is cold, meaning each subscriber starts the work again. An HTTP Observable from HttpClient is cold, so this template sends two requests:
<h2>{{ (user$ | async)?.name }}</h2>
<p>{{ (user$ | async)?.email }}</p>Bind once and reuse the local name instead:
@if (user$ | async; as user) {
<h2>{{ user.name }}</h2>
<p>{{ user.email }}</p>
}If you truly need several independent places to read the same stream, share it in the component with the RxJS shareReplay operator:
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AsyncPipe } from '@angular/common';
import { Observable, shareReplay } from 'rxjs';
interface User {
name: string;
email: string;
}
@Component({
selector: 'app-profile',
standalone: true,
imports: [AsyncPipe],
template: `
<h2>{{ (user$ | async)?.name }}</h2>
<p>{{ (user$ | async)?.email }}</p>
`,
})
export class ProfileComponent {
private http = inject(HttpClient);
user$: Observable<User> = this.http
.get<User>('/api/user')
.pipe(shareReplay({ bufferSize: 1, refCount: true }));
}With shareReplay, both pipe uses share one request and the second subscriber receives the stored value. The refCount: true option lets the source unsubscribe when the last subscriber leaves.
Importing the pipe
In a standalone component, AsyncPipe is not available automatically. Add it to imports, as the example above does. If you forget, Angular reports that the pipe async could not be found.
Combining async with other pipes
The async pipe is an ordinary pipe, so it chains with others. Put parentheses around the async expression when you chain, so that the other pipe receives the resolved value and not the Observable.
<p>{{ (createdAt$ | async) | date:'mediumDate' }}</p>
<p>{{ (price$ | async) | currency:'EUR' }}</p>The built-in date and currency pipes accept null, so they print nothing while the value is still loading. A custom pipe must accept null or undefined explicitly. The truncate pipe you will write in a later chapter does this with its string | null | undefined parameter type, and this is the reason.
Objects from several streams
When a template needs data from several sources, combine them in the component and bind the result once. This keeps the template short and uses one subscription.
import { Component } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { combineLatest, map, of, timer } from 'rxjs';
@Component({
selector: 'app-dashboard',
standalone: true,
imports: [AsyncPipe],
template: `
@if (vm$ | async; as vm) {
<p>{{ vm.user }} has {{ vm.unread }} unread messages.</p>
} @else {
<p>Loading…</p>
}
`,
})
export class DashboardComponent {
private user$ = of('Ada');
private unread$ = timer(500).pipe(map(() => 3));
vm$ = combineLatest({ user: this.user$, unread: this.unread$ });
}combineLatest emits only after every source has emitted at least once. Until then the view shows the loading text.
Promises
The async pipe accepts a Promise as well. It reads the resolved value and shows nothing until then.
@if (config | async; as cfg) {
<p>Theme: {{ cfg.theme }}</p>
}Here config would be a Promise<{ theme: string }> field. A Promise has no unsubscribe, so the pipe only ignores a result that arrives after destruction.
Errors
If the Observable errors, the pipe rethrows the error during change detection, and Angular's error handler reports it. The template does not recover on its own. Handle expected failures in the stream with catchError, and give the template a value to show:
import { catchError, of } from 'rxjs';
users$ = this.http.get<string[]>('/api/users').pipe(
catchError(() => of(null)),
);A null result then falls into the @else branch of your @if, where you can show an error message. If you need to tell "loading" and "failed" apart, emit a small object such as { status: 'error' } instead of null.
Common mistakes
| Mistake | Symptom | Fix | Column |
|---|---|---|---|
| Reading a property of `(x$ \ | async)` without a guard | `Cannot read properties of null` at first render | Use `@if ... as`, `?.`, or `??` |
| Repeating `\ | async` on a cold Observable | Duplicate HTTP requests | Bind once with `as`, or use `shareReplay` |
| Creating the Observable inside a method called from the template | New subscription on every change detection run, flicker, and repeated requests | Assign the Observable to a field once | |
| Forgetting `AsyncPipe` in `imports` | Pipe `async` could not be found | Add `AsyncPipe` to the component's `imports` | |
| Treating a falsy emission as "loading" | `0` or `''` shows the loading branch | Compare with `null` explicitly |
The third mistake deserves a closer look. A template such as @if (loadUser() | async; as user) calls loadUser() on every change detection pass. Each call returns a new Observable, so the pipe sees a different source each time. It then drops its old subscription and subscribes again, which restarts the request and never settles. Create the Observable once, in a field or in the constructor, and bind that field.
When not to use the async pipe
The pipe is the best default for values that only the template reads. It is less convenient when the component class itself needs the value, for example to compute something or to send it elsewhere. In that case, convert the stream to a signal with toSignal from @angular/core/rxjs-interop, or subscribe in code and clean up with takeUntilDestroyed. You can still use the async pipe for the display part and keep a separate subscription for the logic, but then remember that the two do not share a source unless you share it explicitly.
Exercise
A component has user$ = this.http.get<User>('/api/user'). Its template contains <h2>{{ (user$ | async)?.name }}</h2> and <p>{{ (user$ | async)?.email }}</p>. How many HTTP requests are sent, and what are two ways to reduce them to one?
Show answer
Two requests are sent, because each | async creates its own subscription and HttpClient Observables are cold. Fix one: wrap the template in @if (user$ | async; as user) { ... } and read user.name and user.email. Fix two: add .pipe(shareReplay({ bufferSize: 1, refCount: true })) to user$ so both subscriptions share one request.
Exercise
A template uses @if (count$ | async; as count) { <p>{{ count }}</p> } @else { <p>Loading…</p> }, and count$ emits 0 after a second. What does the user see, and how do you change the template so that 0 is displayed?
Show answer
The user sees "Loading…" forever, because 0 is falsy and takes the @else branch. Bind with @let count = count$ | async; and test @if (count !== null), so only the initial null shows the loading text and 0 is rendered.