DEV Community

Saulo Dias
Saulo Dias

Posted on • Edited on

3 1

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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more