Sub topic 6
Displaying Observables with the async pipe
This chapter assumes you know how to subscribe to an RxJS Observable and that you have read the earlier chapters on enabling ChangeDetectionStrategy.OnPush and on what marks an OnPush component for checking. You should also know the difference between a cold Observable (one that starts work per subscriber, such as HttpClient.get) and a hot one (one that shares a single source).
Why the async pipe exists
An OnPush component is checked only when something marks it dirty. An Observable that emits after a timer, a WebSocket message or an HTTP response does not do that by itself. If you subscribe in the class and assign the result to a plain field, the field changes but the view stays stale, because nothing marked the component for checking.
The async pipe handles three jobs at once:
- It subscribes to the Observable (or Promise) when the template first reads it.
- It marks the component for checking each time a new value arrives.
- It unsubscribes when the component is destroyed, or when the template hands it a different Observable.
You do not write subscription code, a markForCheck() call or a cleanup hook.
The basic pattern
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 $ suffix on seconds$ is a naming convention for Observables. Angular does not require it, but it makes templates easier to read.
Three things to note:
- You must import
AsyncPipeinto a standalone component'simportsarray (or into the NgModule that declares the component). - The component has no
ngOnInit, no field that holds the number and nongOnDestroy. - The view updates every second even though the component is OnPush and its inputs never change.
What happens inside the pipe
The pipe is a small stateful object. It keeps a reference to the Observable it is subscribed to, the latest value it received, and an injected ChangeDetectorRef. Each time the template evaluates seconds$ | async, the pipe compares the Observable it is given with the one it already holds:
- If it is the same reference, the pipe returns its stored latest value.
- If it is a different reference, the pipe unsubscribes from the old one, clears the stored value and subscribes to the new one.
- If the Observable emits, the pipe stores the value and calls
markForCheck()on the component's change detector. The next change detection pass then reads the new value.
The pipe is marked impure internally. Angular calls it on every check of the view instead of only when its input reference changes. This is what lets it return a new value even though the Observable reference stays the same. The reference comparison above is cheap, so this costs little.
Handling the first render: null
Before the Observable emits, the pipe returns null. The type of seconds$ | async is therefore number | null. This matters in two places.
First, interpolation shows nothing for null, which is usually what you want. Second, accessing a property of a not-yet-loaded object fails under strict templates, because profile might be null. The usual solution is to wrap the block in @if and alias the resolved value:
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-profile',
imports: [AsyncPipe],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
@if (profile$ | async; as profile) {
<h2>{{ profile.name }}</h2>
<p>{{ profile.email }}</p>
} @else {
<p>Loading...</p>
}
`,
})
export class ProfileComponent {
profile$: Observable<Profile> = inject(HttpClient).get<Profile>('/api/profile');
}The pipe subscribes once. Inside the @if block, profile has the type Profile with no null. The @else block shows while the value is null.
This example needs provideHttpClient() in your application configuration.
<br>
One pipe, one subscription
Every | async in a template creates its own subscription. With a cold Observable, each subscription repeats the work. This template sends two HTTP requests:
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-two-requests',
imports: [AsyncPipe],
template: `
<h2>{{ (profile$ | async)?.name }}</h2>
<p>{{ (profile$ | async)?.email }}</p>
`,
})
export class TwoRequestsComponent {
profile$ = inject(HttpClient).get<{ name: string; email: string }>('/api/profile');
}There are two ways to fix this:
- Alias the value once, as in the
@if ... as profileexample above, and read from the alias. - Share the source with
shareReplay, when several separate places in the template need the same stream.
import { shareReplay } from 'rxjs/operators';
// Inside the component class:
// profile$ = inject(HttpClient)
// .get<Profile>('/api/profile')
// .pipe(shareReplay({ bufferSize: 1, refCount: true }));With refCount: true, the shared source is unsubscribed when the last subscriber leaves. With the default (refCount: false) the source subscription stays alive after the component is destroyed. For an HTTP call that completes, this is harmless. For a long-lived stream, it is a leak.
The mistake that causes an endless loop
The async pipe compares Observable references. If the template expression creates a new Observable on each evaluation, the pipe sees a different reference on every pass:
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
interface Item {
id: number;
label: string;
}
@Component({
selector: 'app-broken-list',
imports: [AsyncPipe],
template: `
<ul>
@for (item of getItems() | async; track item.id) {
<li>{{ item.label }}</li>
}
</ul>
`,
})
export class BrokenListComponent {
private http = inject(HttpClient);
// Returns a NEW Observable on every call.
getItems() {
return this.http.get<Item[]>('/api/items');
}
}Here is what happens on each pass:
- The pipe gets a new Observable, so it unsubscribes from the old one, clears its stored value and subscribes again. A new request goes out.
- The response arrives. The pipe stores the value and calls
markForCheck(). - The next pass calls
getItems()again, which returns yet another Observable. Return to step 1.
The list flickers or stays empty, and the network tab fills with requests. The fix is to create the Observable once and store it in a field:
items$ = this.http.get<Item[]>('/api/items');The same rule applies to pipelines built in the template, such as (source$ | someCustomPipe) | async, when the custom pipe returns a new Observable each time. Build the stream in the class and expose it as a stable field.
Streams that depend on an input
Sometimes the Observable you display depends on an @Input. Do not call a method in the template. Instead, create the stream once and make it react to the input. One way is to keep a BehaviorSubject (a Subject that remembers its latest value) and push new values into it from the input setter:
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-greeting',
imports: [AsyncPipe],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ greeting$ | async }}</p>`,
})
export class GreetingComponent {
private name$ = new BehaviorSubject<string>('');
@Input({ required: true })
set name(value: string) {
this.name$.next(value);
}
greeting$: Observable<string> = this.name$.pipe(map((n) => `Hello, ${n}`));
}The setter runs when the parent passes a new reference, which already triggers an OnPush check. The pipe then reads the new emission. For more complex cases, switchMap on the input stream lets you start a new request and cancel the previous one when the input changes.
Errors, completion and Promises
- Errors. If the Observable errors and nothing handles it, the pipe rethrows the error during change detection. Handle it in the stream with
catchError, and return a fallback value or an error state that the template can show. - Completion. When the Observable completes, the pipe keeps the last value. It does not reset to
null. - Promises. The pipe also accepts a Promise. It shows
nulluntil the Promise resolves, then the resolved value. - Late subscribers. A hot Observable that has already emitted will not replay for the pipe unless it is a replaying source such as
BehaviorSubjectorshareReplay. The view showsnulluntil the next emission.
Async pipe or manual subscription
| Concern | `async` pipe | Manual `subscribe` |
|---|---|---|
| Marks the OnPush component for checking | Yes, automatically | Only if you call `markForCheck()` |
| Cleanup | Automatic on destroy | You must unsubscribe (for example, `takeUntilDestroyed`) |
| Value available in class code | No, only in the template | Yes |
| Multiple reads in one template | One subscription per pipe | One subscription total |
| Side effects such as logging or navigation | Poor fit | Good fit |
Use the pipe when the Observable exists only to display data. Use a manual subscription, with markForCheck() and takeUntilDestroyed, when the class itself needs the values or when the emission triggers a side effect. The next chapter covers that manual route.
<br>
Summary of rules
- Expose Observables as stable fields, not as method calls in the template.
- Use one
| asyncper stream and alias the result with@if ... as, or share the stream withshareReplay. - Expect
nullbefore the first emission and decide what the template shows. - Catch errors in the stream.
- Prefer the pipe for display-only data, and a manual subscription when the class needs the value.
Exercise
A component with OnPush uses @for (row of loadRows() | async; track row.id), where loadRows() returns this.http.get<Row[]>('/api/rows'). The table never fills and the network tab shows a stream of repeated requests. Explain why, and show the fix.
Show answer
Each change detection pass calls loadRows(), which returns a new Observable. The async pipe sees a different reference, unsubscribes from the old one, clears its stored value and subscribes again, so another request goes out. When a response arrives, the pipe calls markForCheck(), which triggers another pass, which creates another new Observable, and the cycle repeats. The value is cleared each time, so the list stays empty. The fix is to create the Observable once in a field: rows$ = this.http.get<Row[]>('/api/rows'); and use @for (row of rows$ | async; track row.id). Because null is not iterable in a way that renders rows, you can also wrap the loop in @if (rows$ | async; as rows) and iterate over rows.
Exercise
A template contains <h2>{{ (user$ | async)?.name }}</h2> and <p>{{ (user$ | async)?.email }}</p>, where user$ is this.http.get<User>('/api/user'). How many HTTP requests are sent, and how do you reduce it to one without changing the service?
Show answer
Two requests, because each async pipe makes its own subscription and HttpClient.get is cold. Either wrap both reads in a single @if (user$ | async; as user) { ... } block and use user.name and user.email, or add .pipe(shareReplay({ bufferSize: 1, refCount: true })) to user$ so both subscriptions share one request.