Sub topic 5
Letting the Template Subscribe with the async Pipe
This chapter assumes you know how an observable is subscribed to and why a forgotten subscription leaks memory, as covered in the previous chapter. It also assumes you can write standalone Angular components with templates.
What the async pipe does
The async pipe is a built-in Angular pipe that subscribes to an observable from the template. It does four jobs for you:
- It subscribes when the view is created.
- It returns the latest emitted value to the template.
- It marks the component for change detection on each emission, so it works with
OnPush. - It unsubscribes when the view is destroyed, or when the observable reference changes.
Your component class only declares the stream. It never calls subscribe(), so there is nothing to clean up by hand.
A worked example
This clock shows the time every second. The interval keeps running only as long as the component is on screen.
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { AsyncPipe, DatePipe } from '@angular/common';
import { interval, map, startWith } from 'rxjs';
@Component({
selector: 'app-clock',
standalone: true,
imports: [AsyncPipe, DatePipe],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
@if (now$ | async; as now) {
<p>The time is {{ now | date: 'mediumTime' }}</p>
}
`,
})
export class ClockComponent {
readonly now$ = interval(1000).pipe(
startWith(0),
map(() => new Date())
);
}The @if (expr | async; as name) form unwraps the value once and gives it a local name. You can then use now as many times as you like inside the block, and the template still holds only one subscription.
Common errors
| Mistake | What happens | Fix | Column |
|---|---|---|---|
| Writing `obs$ \ | async` several times in the template | Each pipe creates its own subscription. On an HTTP stream that means one request per pipe | Unwrap once with `@if (... ; as x)` |
| Binding to a method, such as `getUsers() \ | async` | The method returns a new observable on every change detection run, so the pipe keeps resubscribing | Assign the observable to a field once |
| Expecting a value right away | The pipe returns `null` until the first emission | Use `startWith`, or handle `null` in the template | |
| Wrapping a stream that can emit `0`, `''`, or `false` in `@if` | Angular treats falsy values as "no value" and hides the block | Map to an object, such as `{ value }`, before unwrapping | |
| Forgetting to import `AsyncPipe` | Compile error: the pipe `async` cannot be found | Add `AsyncPipe` to the component's `imports` |
When the reference changes
If you assign a new observable to the bound field, the pipe unsubscribes from the old one and subscribes to the new one. You get switching behavior for free. You also get the method-binding bug above if the new reference arrives by accident.
Exercise
A template contains {{ (user$ | async)?.name }} and {{ (user$ | async)?.email }}, where user$ comes from an HTTP request. The network tab shows two requests. Why does this happen, and how do you fix it?
Show answer
Each async pipe subscribes on its own, and each subscription to the cold HTTP observable sends a new request. Unwrap the value once with @if (user$ | async; as user) { {{ user.name }} {{ user.email }} }. That leaves one subscription and one request.
Exercise
A counter stream emits 0 first, but nothing renders until it reaches 1. The template uses @if (count$ | async; as count). What is wrong?
Show answer
@if treats 0 as falsy, so the block stays hidden. Map the values to an object, as in count$.pipe(map(value => ({ value }))), and render count.value. Alternatively, render {{ count$ | async }} directly without @if.