What is Async pipe?
A great question, one of the most common Angular interview questions.
In short (as in an interview)
Async pipe is an Angular pipe that subscribes to an Observable or Promise in the template and automatically unsubscribes when the component is destroyed.
It also updates the template on new values.
In detail
The async pipe lets you avoid writing subscribe by hand.
Example:
<div>{{ user$ | async }}</div>Angular:
- subscribes to
user$ - updates the template on new values
- unsubscribes in
ngOnDestroy
The equivalent without async pipe
What you would otherwise have to write:
user?: User;
ngOnInit() {
this.user$.subscribe(u => this.user = u);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}async pipe does this automatically.
Working with *ngIf
A very typical Angular pattern:
<div *ngIf="user$ | async as user">
{{ user.name }}
</div>This gives you:
- a subscription
- a local variable
- auto-unsubscribe
What async pipe supports
It works with:
- Observable
- Promise
For example:
<div>{{ promise | async }}</div>Why async pipe matters
In an interview, it's worth mentioning that it:
- prevents memory leaks
- simplifies the code
- automatically triggers change detection
- is the standard Angular approach
A typical follow-up question
Very often asked:
Async pipe vs subscribe?
Answer:
async pipe is better for UI data because:
- there's no manual unsubscribe
- less code
- a declarative approach
subscribe is used when you need side-effect logic.
Another popular question
Does async pipe work with BehaviorSubject?
Yes, because it works with any Observable.
A mini example of an Angular service
A very typical pattern:
users$ = this.http.get<User[]>('/api/users');Template:
<li *ngFor="let user of users$ | async">
{{ user.name }}
</li>This is considered the "clean Angular approach."
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.