All topics
RxJSbeginner

The Async Pipe

Explain how the async pipe subscribes to an Observable/Promise in the template and automatically unsubscribes on destroy.

The async pipe is Angular's built-in way to consume an Observable (or Promise) directly in a template, and interviewers ask about it because it's one of the most impactful, easy-to-adopt best practices in everyday Angular code: it subscribes to the bound Observable automatically, triggers change detection when new values arrive, and — critically — automatically unsubscribes when the component (or the specific template context the pipe is used in) is destroyed, eliminating an entire category of manual subscription-management bugs.

It's like a hotel room's automatic minibar sensor that starts tracking usage the moment you check in and automatically stops and settles the tab the moment you check out — no need for you to remember to manually cancel a service when you leave.

Key Concepts

1
This directly avoids the more error-prone pattern of subscribing manually in the component class (this.data$.subscribe(data => this.data = data)), assigning the result to a plain property, and then having to remember to unsubscribe in ngOnDestroy — with the async pipe, there's no manual subscription to forget to clean up, since Angular's own pipe implementation handles that internally.
this.data$.subscribe(data => this.data = data)ngOnDestroy
2
The as syntax (*ngIf="data$ | async as data", or the newer @if (data$ | async; as data)) is a commonly-paired pattern that both unwraps the Observable's value into a local template variable and gates rendering on it being non-null, avoiding the trap of subscribing to the same Observable multiple times in the same template (once to check truthiness, once again to actually display the value) — each additional | async usage in a template creates its own independent subscription, so reusing a captured as variable is both cleaner and avoids extra, redundant multicasting concerns if the source Observable isn't already shared.
as*ngIf="data$ | async as data"@if (data$ | async; as data)| async
3
A thorough interview answer connects this to the broader idea of keeping components "reactive all the way down" — building an entire component around Observable-based state and consuming it purely through the async pipe in the template (rather than mixing manual subscriptions and plain properties) is a widely recommended pattern precisely because it minimizes the surface area for subscription-related memory leaks.