How to use the ASYNC PIPE in Angular Templates

What is the Angular async pipe?

You can use the async pipe in Angular to automatically subscribe to and unsubscribe from observables, and display data in the template. Did you know you can also use the async pipe to conditionally display another part of the template?

Angular’s async pipe is a pipe that subscribes to an Observable or Promise for you and returns the last value that was emitted.

Angular async pipe

That means we don’t have to do any more of this.

$observable.subscribe((result) => { // do something with the result here });

 And best of all, when the component is destroyed the async pipe will automatically unsubscribe for you. No need to do this manually.

Why should we use Angular’s async pipe?

If you subscribe() to an Observable or Promise you’ll need to unsubscribe() at the end of your component’s life cycle to avoid memory leaks.

We don’t have to unsubscribe manually because the AsyncPipe handles this for us.

Example How to Use Async Pipe In Angular

First You Declare A new Variable Observable Type

app.comonent.ts

import { Component } from '@angular/core';
import { CommonservieService } from './commonservie.service';
import { FormControl, FormGroup } from '@angular/forms';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'inter';
  storedata:any;

  datastore:Observable<any> | any;


  constructor(private _commonservice:CommonservieService){

  }

 

  showdata(){
  
    this.datastore = this._commonservice.getdata();

    
  }



}

app.comopnent.html

<h1>Asyn Pipe</h1>

<ul *ngFor="let data of datastore | async">
  <li>{{data.title}}</li>
</ul>

<button (click)="showdata()">click me</button>

common.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class CommonservieService {


  APIURL='https://fakestoreapi.com/products';
  constructor(private _http:HttpClient) { }

  getdata(){
    return this._http.get(this.APIURL);
  }

}

If you enjoyed reading this post and have found it useful for you, then please give a share with your friends, and follow me to get updates on my upcoming posts. 

if you have any confusion Comment below or you can contact us by filling out our contact us.

YOU MIGHT ALSO LIKE

How to Make Angular CRUD Operation with JSON-Server

How to Translate Website content in Angular

If you have any problem to understand this code you can watch also video tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *