Angular: The power of Async Pipe + Observables.

saulodias

Saulo Dias

Posted on October 29, 2021

Angular: The power of Async Pipe + Observables.

One of the most powerful features when creating Angular components is the Async Pipe. The greatest thing about it is that it allows you to take advantage of asynchronous rendering in your template without having to worry about subscribing and unsubscribing from Observables.

import { Component, OnInit, OnDestroy } from '@angular/core';
import { of, Subject } from 'rxjs';
import { delay, startWith, takeUntil } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  template: `
    <h1>Async example</h1> 
    <h2>Items</h2> 
    <ul>
      <li *ngFor="let item of items | async">{{item}}</li>
    </ul>
    <h2>Other Items</h2> 
    <ul>
      <li *ngFor="let other of otherItems">{{other}}</li>
    </ul>
  `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit, OnDestroy  {

  items = of([1, 2, 3])
    .pipe(
      delay(2000), 
      startWith(['...'])
    );

  // vs 

  otherItems: any[];
  private destroy$ = new Subject();
  ngOnInit() {
    of([1, 2, 3])
      .pipe(
        delay(2000),
        startWith(['...']),
        takeUntil(this.destroy$)
      )
      .subscribe(other  => this.otherItems = other)
  }
  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
}

Enter fullscreen mode Exit fullscreen mode

Check it out on Stackblitz.

As you can see, in the first example, we are rendering a list (items) using the async pipe in the HTML template. There is no need for the additional handling after the component is destroyed, which you can see is not the case for the other list otherItems. That is simply because the async pipe is going to take care of that for you.

💖 💪 🙅 🚩
saulodias
Saulo Dias

Posted on October 29, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related