Angular

What is the purpose of Async pipe in Angular?

What is the purpose of the Async pipe in Angular?

The AsyncPipe subscribes to an observable or promise and returns the latest value it has emitted. When a new value is emitted, the pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

Syntax of AsyncPipe in Angular

 {{obj_expression | async}} 

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. Here is an example of time observable which continuously updates the view for every 2 seconds with the current time.

@Component({
selector: ‘async-observable-pipe’,
template: <div><code>observable|async</code>:Time: {{ time | async }}</div>
})
export class AsyncObservablePipeComponent {
time = new Observable(observer =>
setInterval(() => observer.next(new Date().toString()), 2000)
);
}

Advantages of Using AsyncPipe over Subscribe in Angular

  1. Using subscribe() we always make sure to unsubscribe at the end of the component life-cycle to avoid memory leaks which is not the case with AsyncPipe in Angular.
  2. Using subscribe unwraps property to be used in multiple places in the template “as it is” without the need to rely on various workarounds.

Leave a Comment