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. You should also know what an Observable is: a stream that can emit values over time.
Why the async pipe exists
Data from an HTTP call or a store often arrives later than the template renders. The usual approach is to call subscribe() in the component, copy each value into a field, and call unsubscribe() when the component is destroyed. That is three places to get wrong.
The async pipe does all three jobs inside the template. It subscribes to an Observable or Promise, returns the latest value it has emitted, and marks the component for a check when a new value arrives. When the component is destroyed, it unsubscribes. Before the first value arrives, it returns null.
Basic usage
import { Component } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { Observable, of, delay } from 'rxjs';
interface User {
name: string;
}
@Component({
selector: 'app-user',
standalone: true,
imports: [AsyncPipe],
template: `
@if (user$ | async; as user) {
<p>{{ user.name }}</p>
} @else {
<p>Loading…</p>
}
`,
})
export class UserComponent {
user$: Observable<User> = of({ name: 'Ada' }).pipe(delay(1000));
}Three details matter here:
AsyncPipemust be listed inimports. Built-in pipes such asdatecome with common template features, butasyncis a standalone pipe you import like any other.as userstores the emitted value in a template variable, so you subscribe once and use the value several times.- The
@elsebranch runs while the value isnull, which makes it a natural loading state.
By convention, Observable fields end with $.
Subscribe once
Each | async in a template creates its own subscription. Two uses of user$ | async on a cold Observable, such as an HTTP request, send two requests.
<!-- Two subscriptions: two HTTP requests -->
<p>{{ (user$ | async)?.name }}</p>
<p>{{ (user$ | async)?.email }}</p>Bind once with as and reuse the variable:
@if (user$ | async; as user) {
<p>{{ user.name }}</p>
<p>{{ user.email }}</p>
}If you cannot restructure the template, share the stream in the component with the RxJS shareReplay operator.
Combining async with other pipes
The async pipe returns a plain value, so you can chain other pipes after it. Wrap the async expression in parentheses first:
<p>{{ (createdAt$ | async) | date:'mediumDate' }}</p>
<p>{{ (total$ | async) | currency:'EUR' }}</p>The built-in date and currency pipes accept null and return null, so the output stays empty until the first value arrives. A custom pipe must handle null itself. This is why the TruncatePipe from the custom pipes chapter accepts string | null | undefined.
Lists and the empty case
An empty array is truthy in an @if, so an as binding cannot tell "still loading" from "loaded, but empty". Check the length yourself:
@if (items$ | async; as items) {
@for (item of items; track item.id) {
<li>{{ item.name }}</li>
} @empty {
<li>No items found.</li>
}
} @else {
<p>Loading…</p>
}The @else runs only while the pipe returns null. Once the array arrives, even an empty one, the @if branch renders, and @empty handles the no-results message.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `No pipe found with name 'async'` | `AsyncPipe` is missing from `imports` | Add `AsyncPipe` to the component's `imports` |
| Duplicate network requests | Several `async` pipes on one cold Observable | Use one `as` binding or `shareReplay` |
| Template shows nothing, then a value | The pipe returns `null` first | Add an `@else` loading state |
| Type error that a value may be `null` | The pipe's type includes `null` | Use `@if (... ; as x)` so `x` is non-null inside |
| Error thrown in the console | The Observable errored and the pipe rethrows | Handle errors with `catchError` in the stream |
Exercise
A template contains <p>{{ (price$ | async) | currency:'USD' }}</p> and <p>{{ (price$ | async) | percent }}</p>, where price$ wraps an HTTP call. What problem does this have, and how do you fix it in the template?
Show answer
Each async pipe subscribes separately, so the HTTP request is sent twice. Wrap the content in @if (price$ | async; as price) { ... } and use price in both expressions. Keep in mind that a price of 0 is falsy, so the @if would hide it. Use @if ((price$ | async) !== null; ...) or wrap the value in an object if zero is valid.