Monday, December 14, 2020

Async Pipe in Angular With Examples

Of all the built-in pipes in Angular, Async pipe is a little different as it subscribes to an Observable or Promise and returns the latest value it has emitted. When the component gets destroyed, the async pipe unsubscribes automatically to avoid any memory leaks.


Advantages of using Async pipe

The advantages of using Async pipe are as follows-

  1. Asyn pipe makes using the Observable or Promise easier than using them directly.
  2. For Promise, it automatically calls the then method.
  3. For Observable it automatically calls the subscribe and unsubscribe methods.

Async pipe with Promise Angular example

In the example we’ll first use the Promise directly and then using Async pipe so that you can see what benefit you get by using Async pipe.

Component class (app.component.ts)

Here we have a method that returns a Promise after 2 seconds. When Promise is resolved data is assigned to a field newValue.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html', 
})
export class AppComponent{
  newValue: string;
  constructor(){
    this.getValue().then(v => this.newValue = v);
  }

  getValue(){
    return new Promise<string>((resolve, reject) => {
      setTimeout(() => resolve("Value from Promise"), 2000);
    });
  }
}

Template (app.component.html)

<div class="container">
 {{ newValue }}
</div>

By using Angular async pipe you can directly bind to the Promise. There is no need to call then() method and extra field is not needed to store the resolved value. You can have a field of type Promise itself. Async will automatically call the then() method on it.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html', 
})
export class AppComponent{
  promise: Promise<string>;
  constructor(){
    this.promise = this.getValue();
  }

  getValue(){
    return new Promise<string>((resolve, reject) => {
      setTimeout(() => resolve("Value from Promise"), 2000);
    });
  }
}

Template (app.component.html)

<div class="container">
 {{ promise | async }}
</div>

Async pipe with Observable Angular example

In the example we’ll first use the Obesrvable directly and then using Async pipe so that you can see what benefit you get by using Async pipe.

Component class (app.component.ts)

Here we’ll create a simple observable that just emits an incremented value every 1 second. As you can see Component class implements OnDestroy too in order to unsubscribe from the Observable manually.

You also need one extra field (newValue) to store the emitted value.

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Observable, Observer, Subscription } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html', 
})
export class AppComponent implements OnInit, OnDestroy{
  newValue: number;
  observable: Observable<number>;
  subscription: Subscription;
  ngOnInit() {
    this.observable = new Observable((observer: Observer<number>) => {
      let value = 0
      setInterval(
        () => {
          observer.next(value++);
        }, 1000);
    });
    this.subscription = this.observable.subscribe((value: number) => {
      this.newValue = value;
    });
  }
  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }
}

Template (app.component.html)

<div class="container">
  {{ newValue }}
</div>

Now same thing when done using Async pipe in Angular.

In the component class there is no need to implement OnDestroy as unsubscribing happens automatically with Async pipe. There is no need to subscribe to the Observable too as that also happens automatically.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html', 
})
export class AppComponent implements OnInit{
  observable: Observable<number>;
  subscription: Subscription;
  ngOnInit() {
    this.observable = new Observable((observer: Observer<number>) => {
      let value = 0
      setInterval(
        () => {
          observer.next(value++);
        }, 1000);
    });
  }
}

Template (app.component.html)

<div class="container">
  {{ observable | async }}
</div>

That's all for this topic Async Pipe in Angular With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Pure and Impure Pipes in Angular
  2. Using Angular Pipes in Component or Service Classes
  3. Custom Pipe in Angular With Example
  4. How to Create a Custom Observable in Angular
  5. Angular Cross Component Communication Using Subject Observable

You may also like-

  1. How to Install Node.js and NPM in Windows
  2. Angular Route - Passing Static Data
  3. Angular ngSwitch Directive With Examples
  4. Custom Async Validator in Angular Reactive Form
  5. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  6. Synchronization in Java - Synchronized Method And Block
  7. Reflection in Java - Getting Method Information
  8. List Comprehension in Python With Examples

No comments:

Post a Comment