Sub topic 6
Displaying Observables with the async pipe
This chapter assumes you know basic RxJS (Observables and subscriptions), have used component inputs, and have read the previous chapters on what marks an OnPush component for checking.
The problem the pipe solves
An OnPush component is checked only when an input gets a new reference, an event fires inside it, or it is marked for checking. Data that arrives later breaks that rule. A timer tick, an HTTP response, or a WebSocket message changes nothing the component can see. If you subscribe by hand and assign the value to a field, the field changes but the view stays stale.
The async pipe handles this. It does three jobs:
- It subscribes to the Observable when the template is first rendered.
- It stores the latest emitted value and calls
markForCheck()on each emission. That schedules the component, and its ancestors up to the root, for the next change detection pass. - It unsubscribes when the component is destroyed or when the bound Observable reference changes.
A first example
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { Observable, timer } from 'rxjs';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-clock-ticks',
imports: [AsyncPipe],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Seconds elapsed: {{ seconds$ | async }}</p>`,
})
export class ClockTicksComponent {
seconds$: Observable<number> = timer(0, 1000).pipe(map((n) => n));
}The component has no ngOnInit, no ngOnDestroy, and no ChangeDetectorRef. The pipe does all of that work. The $ suffix on seconds$ is a convention that marks a field as an Observable.
The diagram shows what happens on each emission.
Handling the "not yet" state
Before the first emission, the pipe returns null. An HTTP request has no value until the response arrives, so templates usually need a loading state. The @if block with an as alias handles this and also reads the value only once:
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
interface Profile {
name: string;
email: string;
}
@Component({
selector: 'app-user-profile',
imports: [AsyncPipe],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
@if (profile$ | async; as profile) {
<p>{{ profile.name }} ({{ profile.email }})</p>
} @else {
<p>Loading...</p>
}
`,
})
export class UserProfileComponent {
private http = inject(HttpClient);
profile$: Observable<Profile> = this.http.get<Profile>('/api/profile');
}This example needs provideHttpClient() in your application providers.
Common errors
One subscription per pipe
Each | async in a template creates its own subscription. http.get is a cold Observable, so two pipes on profile$ send two requests. Use the @if (... ; as alias) form shown above, so the template subscribes once and reuses the alias. You can also share the stream with shareReplay({ bufferSize: 1, refCount: true }).
Building the Observable in the template
Do not call a method or getter that returns a new Observable from the template:
// Avoid: each change detection pass creates a new Observable.
get profile$() {
return this.http.get<Profile>('/api/profile');
}The pipe sees a new reference on each pass. It unsubscribes from the old one and subscribes to the new one, which can send a request on every check. Create the Observable once, in a field or in the constructor.
Truthiness checks on emitted values
@if (count$ | async; as count) hides the block when the value is 0, '', or false, because the condition is falsy. If those values are valid, compare against null explicitly, or wrap the value in an object.
Mixing manual subscriptions with the pipe
If you must subscribe by hand to set a field, you need markForCheck() yourself, as the next chapter shows. Use the pipe wherever the value is only displayed.
Choosing between them
| Situation | Choice |
|---|---|
| Value is only shown in the template | `async` pipe |
| Value is needed in TypeScript logic as well | Manual subscription, or convert with `toSignal` |
| Several template bindings need the same stream | One `@if ... as` alias, or `shareReplay` |
Exercise
A component uses {{ (items$ | async)?.length }} in one place and @for (item of items$ | async; track item.id) in another. items$ comes from http.get. How many HTTP requests are sent, and how do you reduce it to one?
Show answer
Two requests, because each | async makes its own subscription to a cold Observable. Wrap the template in @if (items$ | async; as items) { ... } and use items.length and items inside it. Or add shareReplay({ bufferSize: 1, refCount: true }) to items$.