Sub topic 5
Letting the Template Subscribe with the async Pipe
This chapter assumes you already know how to subscribe to an observable and unsubscribe from it by hand, and that you understand why a forgotten subscription leaks memory. You should also be comfortable with standalone components and Angular's built-in control flow (@if, @for). Here we hand subscription management to the template, where the async pipe can handle it for you.
What the async Pipe Does
The async pipe is a built-in Angular pipe that takes an observable (or a Promise) and returns the latest value it emitted. Behind that one expression, it does four jobs:
- Subscribes to the observable when the template first evaluates the expression.
- Stores the latest value and returns it every time change detection runs.
- Marks the component for check each time a new value arrives, so the view updates even under
OnPushchange detection. - Unsubscribes when the component is destroyed, or when the expression starts returning a different observable instance.
The fourth job is the reason the pipe exists. You never call subscribe() or unsubscribe(), so the leak you studied in the previous chapter cannot happen through this path.
A First Example: A Ticking Clock
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { AsyncPipe, DatePipe } from '@angular/common';
import { interval, map } from 'rxjs';
@Component({
selector: 'app-clock',
standalone: true,
imports: [AsyncPipe, DatePipe],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ now$ | async | date: 'mediumTime' }}</p>`,
})
export class ClockComponent {
now$ = interval(1000).pipe(map(() => new Date()));
}The class has no ngOnInit, no ngOnDestroy, and no Subscription field. The component declares what the stream is, and the template decides when to listen. When the clock is removed from the page, for example by an @if turning false, the interval stops.
AsyncPipe must appear in the standalone component's imports array. If you forget it, the compiler reports that no pipe named async was found.
Binding the Value Once with @if and as
You often need the emitted value in several places. Use @if with an as alias to unwrap it once:
import { Component } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { Observable, of, delay } from 'rxjs';
interface Profile {
name: string;
email: string;
}
@Component({
selector: 'app-profile',
standalone: true,
imports: [AsyncPipe],
template: `
@if (profile$ | async; as profile) {
<h2>{{ profile.name }}</h2>
<p>{{ profile.email }}</p>
} @else {
<p>Loading...</p>
}
`,
})
export class ProfileComponent {
profile$: Observable<Profile> = of({ name: 'Ada', email: '[email protected]' }).pipe(
delay(500)
);
}Inside the block, profile has the type Profile, not Profile | null, because @if narrows it. The @else branch covers the period before the first emission, and that gives you a loading state for free.
Common Errors and Gotchas
The first value is null
Before the observable emits, async returns null. The pipe's return type is T | null, so with strict templates, binding {{ (profile$ | async).name }} is a compile error. Use @if ... as, the safe-navigation operator (?.), or an initial value from a source that emits synchronously.
Falsy values hide content
@if tests truthiness. If a stream emits 0, '', or false, the block disappears even though the value is valid:
import { Component } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { of } from 'rxjs';
@Component({
selector: 'app-unread',
standalone: true,
imports: [AsyncPipe],
template: `
<!-- Broken: shows nothing when count is 0 -->
@if (unread$ | async; as count) {
<p>Unread: {{ count }}</p>
}
<!-- Fixed: an object literal is always truthy -->
@if ({ count: unread$ | async }; as vm) {
<p>Unread: {{ vm.count ?? 0 }}</p>
}
`,
})
export class UnreadComponent {
unread$ = of(0);
}Wrapping the values in an object literal, usually called a view model, keeps the block rendered. You can put several streams into one object: { items: items$ | async, count: count$ | async }. A later chapter shows how to build a single view-model stream with combineLatest.
Each async pipe is a separate subscription
Every | async in a template creates its own subscription. With a cold observable, which runs its producer once per subscriber, that repeats the work:
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
interface User {
name: string;
email: string;
}
@Component({
selector: 'app-user-card',
standalone: true,
imports: [AsyncPipe],
template: `
<!-- Two pipes, two HTTP requests -->
<p>{{ (user$ | async)?.name }}</p>
<p>{{ (user$ | async)?.email }}</p>
`,
})
export class UserCardComponent {
private http = inject(HttpClient);
user$ = this.http.get<User>('/api/user');
}The Network tab shows two identical requests. The fix is one subscription bound with @if (user$ | async; as user), or sharing the stream with shareReplay, which a later chapter covers.
Never pass a method call to the pipe
// Inside a component class: do not do this
loadUser() {
return this.http.get<User>('/api/user');
}
// Template: {{ (loadUser() | async)?.name }}Every change-detection pass calls loadUser(), which returns a new observable instance. The pipe sees a different reference, unsubscribes from the old one, and subscribes to the new one. When the response arrives, the pipe marks the view for check, change detection runs again, and a new request goes out. The result is an endless loop of requests. Always assign the observable to a field once, as in user$ = this.http.get<User>(...).
Swapping observables is safe
Because of that same reference check, you can deliberately replace the observable in a field. For example, you might rebuild user$ when an input changes. The pipe drops the old subscription and starts the new one, so nothing leaks.
Errors end the stream
If the observable errors, the pipe reports the error to Angular's ErrorHandler, and the subscription ends. The view keeps showing the last value it received, with no clue that anything failed. Handle errors inside the stream before they reach the template. The error-handling chapter shows how.
async Pipe vs Manual Subscription
| Concern | async pipe | Manual `subscribe()` |
|---|---|---|
| Unsubscribe on destroy | Automatic | You must arrange it (`takeUntilDestroyed`, `unsubscribe`) |
| `OnPush` updates | Automatic `markForCheck` | You must trigger change detection yourself |
| Value available in class code | No, only in the template | Yes, stored in a field |
| Side effects (logging, navigation) | Poor fit | Natural fit |
| Risk of duplicate subscriptions | One per pipe usage | One per `subscribe` call |
Prefer the async pipe when the value exists only to be displayed. Choose a manual subscription with takeUntilDestroyed when the result drives an action, such as navigating after a save, or when class code needs the value.
Promises Work Too
The pipe also accepts a Promise. It calls then on it and returns the resolved value. There is nothing to cancel, so on destroy the pipe simply ignores the late result. Observables remain the better choice for anything that emits more than once or needs cancellation.
Exercise
A template contains {{ (orders$ | async)?.length }} in a header and @for (o of (orders$ | async); track o.id) { ... } in the body. orders$ is an HttpClient GET stored in a field. What happens at runtime, and how do you fix it without adding new operators?
Show answer
Each | async creates its own subscription, and HttpClient observables are cold, so two GET requests are sent. Fix it by subscribing once: wrap both sections in @if (orders$ | async; as orders) { ... } and use orders.length and @for (o of orders; track o.id) inside the block.
Exercise
A badge uses @if (cartCount$ | async; as n) { <span>{{ n }}</span> }. Users report the badge vanishes when the cart is empty instead of showing 0. Explain why and rewrite the template line.
Show answer
@if tests truthiness, and 0 is falsy, so the block is removed. Wrap the value in an object literal, which is always truthy: @if ({ n: cartCount$ | async }; as vm) { <span>{{ vm.n ?? 0 }}</span> }.
Exercise
Why does {{ (getProducts() | async)?.length }}, where getProducts() returns this.http.get(...), cause a flood of network requests?
Show answer
Each change-detection pass calls getProducts(), which returns a new observable instance. The async pipe sees a new reference, unsubscribes from the old one, and subscribes to the new one, which sends another request. Each response marks the view for check and starts the cycle again. Assigning the observable to a field once breaks the loop.