Outline
The async
pipe is a special kind of impure pipe that either waits for a
promise to resolve to display data or subscribes to an observable to display
the emitted values. The Async pipe saves boilerplate in the component code. The component doesn't have to subscribe to the async data source, extract the resolved values and expose them for binding, and have to unsubscribe when it's destroyed (a potent source of memory leaks). Let's see an example of this in action.
app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { Observable, interval } from 'rxjs';
import { map, takeWhile, finalize } from 'rxjs/operators';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
countCompleted = false;
countDown = 5;
count$: Observable<number>;
message = 'Happy Birthday!';
ngOnInit() {
const timer = interval(1000);
this.count$ = timer.pipe(
map(i => this.countDown - i),
takeWhile(i => i > 0),
finalize(() => (this.countCompleted = true))
);
}
}
app.component.html
<h2 *ngIf="!countCompleted">{{ count$ | async }}</h2>
<h2 *ngIf="countCompleted">{{ message }}</h2>
We can also see this example live:
Here we're creating an observable in AppComponent
which counts down from 5
over a 1 second interval. In our template, we're displaying the current count
using the async
pipe. When the countdown is over, we replace the count with
a message saying "Happy birthday!". We can customize where we want to start
the count at and the message we display afterwards in the constructor of
AppComponent
.