When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks. We can use the async pipe in Angular application by including the CommonModule which exports all the basic Angular directives and pipes, such as NgIf, NgForOf, DecimalPipe, and so on. These are then re-exported by BrowserModule, which is included automatically in the root AppModule, when you create a new app with the CLI new command
The async pipe in angular will subscribe to an Observable or Promise
Syntax of AsyncPipe
The below syntax shows how we can use the async pipe with the object expression.
{{obj_expression | async}}
Using AsyncPipe with Promises
Async pipe for promises automatically adds a then callback and renders the response. Now let’s see an example where we are binding a Promise to the view. Clicking the Resolve button resolves the promise.
@Component({
selector: ‘async -pipe’,
template: <div>
<code>promise|async</code>:
<button (click)="clicked()">{{ arrived ? 'Reset' : 'Resolve' }}</button>
<span>Wait for it... {{ logMessage | async }}</span>
</div>
})
export class AsyncPipeComponent {
logMessage: Promise|null = null;
arrived: boolean = false;
private resolve: Function|null = null;
constructor() { this.reset(); }
reset() {
this.arrived = false;
this.logMessage = new Promise((resolve, reject) => { this.resolve = resolve; });
}
clicked() {
if (this.arrived) {
this.reset();
} else {
this.resolve !(‘hi there!’);
this.arrived = true;
}
}
}
typescript
In the above example, we pipe the output of our promise to the async pipe. The property promise is the actual unresolved promise that gets returned from logMessage without then being called on it.