How to Use Async Pipe in Angular

October 20, 2020

Introduction

Built-in Angular Pipes are easily implemented within the Angular template syntax and are practical for handling common formatting tasks.

An Async Pipe allows you to detect changes and propagate asynchronous events directly in the template without changing the data’s underlying value.

Find out how to use Async Pipes to subscribe to Observables and Promises.

How to use Async Pipe in Angular

What is an Async Pipe?

An Async Pipe is a built-in Angular feature that allows you to subscribe and automatically unsubscribe from objects. When subscribed to an Observable or Promise, the Async Pipe creates a copy of the latest emitted output, modifies its format, and displays the resulting value directly in the view. The Async Pipe uses a straightforward syntax:

{{ obj_expression | async }}

You can also use Async Pipes to avoid unnecessary Angular change detection runs and apply checks only to Observables that receive new values.

When to Use Async Pipes?

By default, Angular runs change detection on all components before updating the DOM. This process can potentially drain system resources and negatively affect your app.

Using Async Pipes with the OnPush change detection strategy can improve web application performance. By setting the ChangeDetector class to <strong>OnPush</strong>, only an Observable that registers a new value needs to go through the change detection process.

Default angular detection mode vs onpush angular detection mode

The OnPush mode uses the Async Pipe to inform Angular that the component only tracks value changes originating from its parent. Angular does not need to check the component if there were no changes registered in the parent component.

Additionally, an Async Pipe streamlines Angular’s change detection process by subscribing and automatically unsubscribing from a component precisely at the end of its life cycle. You no longer need to unsubscribe from an Observable or Promise manually. Async Pipes guarantee that redundant subscriptions do not remain open after the component is destroyed and result in a potential memory leak.

Using Async Pipes with Observables

You can subscribe to an Observable object to track changes and pass functions that execute on specific events. An Async Pipe automates this process by consuming the values from the observable data stream and exposing the resolved values for binding.

In this example, an Async Pipe is used with the *ngFor directive to resolve an observable to an array type.

import {Component} from '@angular/core';
import {Observable, of} from 'rxjs';

@Component({
  selector: 'async-observable-pipe',
  template: `<ul><li *ngFor="let d of uList | async">{{d}}</li></ul>`

})
export class AppComponent {

  uList: Observable<number[]>;

  constructor() {
    this.uList = this.getData();
  }

  getData(): Observable<number[]> {
      return of([1,2,3,4,5,6,7,8]);
  }
}

The Async Pipe maintains the subscription to the Observable and continues to deliver values in real-time.

Angular async pipe example

Once the observed component is destroyed, the Async Pipe categorically unsubscribes from the Observable.

Using Async Pipes with Promises

You can use the Promise function to resolve a value asynchronously. Promises are limited to a one call cycle, either a resolve call with a single fulfillment value or a reject call with a single error message.

We need to evaluate the resulting value asynchronously and display it directly. You can use the result to call an API that:

  1. Returns a promise.
  2. Passes that promise into the binding using the Async Pipe.
  3. Returns the new value and displays it in the view.
@Component({
  selector: 'async-promise-pipe',
  template: `<div>
    <code>promise|async</code>:
    <button (click)="clicked()">{{ arrived ? 'Reset' : 'Resolve' }}</button>
    <span>Wait for it... {{ greeting | async }}</span>
  </div>`
})
export class AsyncPromisePipeComponent {
  greeting: Promise<string>|null = null;
  arrived: boolean = false;

  private resolve: Function|null = null;

  constructor() {
    this.reset();
  }

  reset() {
    this.arrived = false;
    this.greeting = new Promise<string>((resolve, reject) => {
      this.resolve = resolve;
    });
  }

  clicked() {
    if (this.arrived) {
      this.reset();
    } else {
      this.resolve!('hi there!');
      this.arrived = true;
    }
  }
}

If a promise needs to return a value on an event such as a user click, the promise is going to resolve on the first click. Observables offer more flexibility and can perform the same function for multiple user clicks.

Conclusion

You now have a better understanding of Async Pipes and how to use them to subscribe and unsubscribe to Observables and Promises.

Implementing Async Pipes in the right use cases makes the Angular change detection process more efficient and ultimately improve end-user experience.

If you are new to Angular, learn how to install Angular on Windows.

About the author
Vladimir Kaplarevic
Vladimir is a resident Tech Writer at CCBill. He has more than 8 years of experience in implementing e-commerce and online payment solutions with various global IT services providers. His engaging writing style provides practical advice and aims to spark curiosity for innovative technologies.
Talk to a Merchant Support Specialist