DEV Community

Saulo Dias
Saulo Dias

Posted on • Updated on

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';

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

  items = of([1, 2, 3])

  // vs 

  otherItems: any[];
  private destroy$ = new Subject();
  ngOnInit() {
    of([1, 2, 3])
      .subscribe(other  => this.otherItems = other)
  ngOnDestroy() {

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.

Top comments (0)