Async Pipe In Angular


What is the async pipe in Angular?

The async pipe in Angular is a pipe that we use to automatically subscribe to an Observable or Promise and then unwrap the data emitted within our template.

Say we use an Observable to fetch data from an API.

export class AppComponent implements OnInit {
    data$: Observable<any>;

    constructor(private httpClient:HttpClient) { }

    ngOnInit() {
        this.data = this.httpClient.get<any>("/data.json");
    }
}

We can use the async pipe in Angular to render that data in our components template.

<div>
    {{ data$  | async }}
</div>

By using the Angular async pipe, it is easier to work with asynchronous data in your Angular components by handling subscriptions and automatic updates when new data arrives.

How to use the async pipe with *ngIf?

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

@Component({
  selector: 'app-timer',
  template: `
    <p *ngIf="($observable | async) as time">Current Timer Value: {{ time }}</p>
  `,
  styleUrls: ['./timer.component.css']
})
export class TimerComponent implements OnInit {

  $observable: Observable<Number>;

  constructor() { }

  ngOnInit(): void {
    this.$observable = timer(5000, 1000);
  }
}

How to use the async pip with *ngFor

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

@Component({
  selector: 'app-people',
  template: `
    <ul>
      <li *ngFor="let user of $users | async">{{user}}</li>
    </ul>
  `,
  styleUrls: ['./people.component.css']
})
export class PeopleComponent implements OnInit {

  $users: Observable<string[]>;

  constructor() { }

  ngOnInit(): void {
    this.$users = of(['Alice', 'Jane', 'Dan', 'Mary'])
  }
}

Let's go async...

The Angular async pipe is very useful!

And I think it's reasonable to say that a well-designed Angular application should never need to subscribe to an Observable.

The async pipe can take care of subscribing and unsubscribing while we worry about more important stuff like the structure of our Angular application and so forth.

What do you think of the AsyncPipe?