How to Use Async Pipe with Observable in Angular
In Angular, use the
async pipe in your template to subscribe to an Observable and get its latest value automatically. This pipe handles subscription and unsubscription for you, simplifying your code and preventing memory leaks.Syntax
The async pipe is used in Angular templates to unwrap values from Observable or Promise objects. It subscribes to the observable and returns the latest emitted value.
observable$ | async: Subscribes toobservable$and returns its latest value.- The pipe automatically unsubscribes when the component is destroyed.
html
<div>{{ observable$ | async }}</div>Output
Displays the latest value emitted by observable$
Example
This example shows a component that uses an observable emitting a string every second. The template uses the async pipe to display the current value automatically.
typescript
import { Component } from '@angular/core'; import { interval } from 'rxjs'; import { map } from 'rxjs/operators'; @Component({ selector: 'app-async-pipe-example', template: ` <h2>Async Pipe Example</h2> <p>Current count: {{ counter$ | async }}</p> ` }) export class AsyncPipeExampleComponent { counter$ = interval(1000).pipe( map(count => `Count is ${count}`) ); }
Output
Current count: Count is 0 (then updates every second: Count is 1, Count is 2, ...)
Common Pitfalls
Common mistakes when using the async pipe include:
- Trying to subscribe manually in the component when using
asyncpipe, causing duplicate subscriptions. - Not using the
$suffix convention for observables, which can confuse code readers. - Using
asyncpipe on non-observable or non-promise values, which will not work.
Always let the async pipe handle subscription to avoid memory leaks.
typescript/html
/* Wrong: manual subscription and async pipe together */ this.observable$.subscribe(value => this.value = value); <!-- Template --> <div>{{ observable$ | async }}</div> /* Right: use async pipe only */ <!-- Template --> <div>{{ observable$ | async }}</div>
Quick Reference
| Usage | Description |
|---|---|
| {{ observable$ | async }} | Subscribe and display latest value from observable$ |
| {{ promise | async }} | Subscribe and display resolved value from promise |
| async pipe | Automatically unsubscribes on component destroy |
| Use with observables | Works only with Observable or Promise types |
Key Takeaways
Use the async pipe in templates to subscribe to observables and get their latest values automatically.
The async pipe handles subscription and unsubscription, preventing memory leaks.
Avoid manual subscriptions in the component when using the async pipe.
Use the $ suffix naming convention for observables to improve code clarity.
The async pipe works only with Observable or Promise types, not plain values.