Angular Async Pipe Example

By Arvind Rai, June 18, 2020
On this page we will provide Angular Async Pipe example. It unwraps a value from an asynchronous primitive. If we have Observable or Promise instance then we use it directly with AsyncPipe using directive such as NgFor, NgIf and NgSwitch. AsyncPipe belongs to angular common module. AsyncPipe subscribes to Observable or Promise and returns the latest data. It plays the role that marks the component to check for data changes. AsyncPipe is used as follows.
<div>{{ observableTime | async }} </div> 
In our example we will access book details using a HTTP URL and iterate the data using NgFor. We will display current time using AsyncPipe. We will also provide how to use AsyncPipe with NgIf and NgSwitch directive. Let us find the complete example step by step.

Software Used

Find the software used in our demo.
1. Angular 9.1.11
2. Node.js 12.5.0
3. NPM 6.9.0

Create Service

First of all we are creating a service. Here we are creating different methods that will be used for AsyncPipe demo.
book.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Subscriber } from 'rxjs';
import { Book } from './book';

@Injectable({
	providedIn: 'root'
})
export class BookService {
	url = "api/books";
	constructor(private http: HttpClient) { }
	//Returns Observable<Book[]>
	getBooksWithObservable(): Observable<Book[]> {
		return this.http.get<Book[]>(this.url);
	}
	//Returns Promise<Book[]>
	getBooksWithPromise(): Promise<Book[]> {
		return this.http.get<Book[]>(this.url).toPromise();
	}
	//Returns Observable<string>
	getCurrentTime(): Observable<string> {
		return new Observable<string>((observer: Subscriber<string>) => {
			//1 second interval
			setInterval(() => observer.next(new Date().toString()), 1000);
		});
	}
	//Returns Promise<Book> 
	getBookSlowly(): Promise<Book> {
		return new Promise(resolve => {
			let book = new Book();
			book.id = 100;
			book.name = 'jQuery Tutorials';
			// Delay by 3 second
			setTimeout(() => resolve(book), 3000);
		});
	}
} 
Find the description of the method and classes used in our service.
Observable: This is a stream of events that can be processed with array-like operators. Every HTTP service method returns an Observable.
Promise: It is a proxy for a value not necessarily known when the promise is created. It does not return immediately a final value. It returns a promise to supply the value at some point in the future.
toPromise(): This is a RxJS operator that converts Observable into Promise.
setInterval(): Sets a time interval after which it re-executes.
setTimeout(): Sets a timeout after which method executes.

Find the test data for Angular In-Memory Web API.
test-data.ts
import { InMemoryDbService } from 'angular-in-memory-web-api';

export class TestData implements InMemoryDbService {
  createDb() {
    let books = [
        {id: 1, name: "Core Java"},
        {id: 2, name: "Angular 2"},
        {id: 3, name: "Hibernate"},
        {id: 4, name: "Spring"}
      ];
    return { books : books };
  }
} 
book.ts
export class Book {
   id: number;
   name: string;
   constructor() { 
   }
} 

AsyncPipe with Observable using NgFor

Here we will use AsyncPipe with Observable using NgFor as follows.
observable.component.html
<h3>AsyncPipe with Observable using NgFor</h3>
<ul>
  <li *ngFor="let book of observableBooks | async" >
    Id: {{book.id}}, Name: {{book.name}}
  </li>
</ul> 
observable.component.ts
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';

import { BookService } from './book.service';
import { Book } from './book';

@Component({
   selector: 'app-observable',
   templateUrl: './observable.component.html'
})
export class ObservableComponent implements OnInit { 
   observableBooks: Observable<Book[]>
   constructor(private bookService: BookService) { }
   ngOnInit(): void {
        this.observableBooks = this.bookService.getBooksWithObservable();
   }
} 

AsyncPipe with Promise using NgFor

Here we will use AsyncPipe with Promise using NgFor as follows.
promise.component.html
<h3>AsyncPipe with Promise using NgFor</h3>
<ul>
  <li *ngFor="let book of promiseBooks | async" >
    Id: {{book.id}}, Name: {{book.name}}
  </li>
</ul> 
promise.component.ts
import { Component, OnInit } from '@angular/core';

import { BookService } from './book.service';
import { Book } from './book';

@Component({
   selector: 'app-promise',
   templateUrl: './promise.component.html'
})
export class PromiseComponent implements OnInit { 
   promiseBooks: Promise<Book[]>
   constructor(private bookService: BookService) { }
   ngOnInit(): void {
	this.promiseBooks = this.bookService.getBooksWithPromise();
   }
} 

AsyncPipe with NgIf and NgSwitch

Find AsyncPipe with NgIf and NgSwitch.
data.component.html
<h3>AsyncPipe with NgIf</h3>

<div *ngIf="promiseBook | async as book; else loading">
   Id: {{book.id}}, Name: {{book.name}}
</div>   
<ng-template #loading>Loading Data...</ng-template>

<h3>AsyncPipe with NgSwitch</h3>

<div [ngSwitch]="(promiseBook | async)?.id">
  <div *ngSwitchCase="100">Find Actual Data</div>
  <div *ngSwitchDefault>Showing Default Data</div>
</div> 
data.component.ts
import { Component, OnInit } from '@angular/core';

import { BookService } from './book.service';
import { Book } from './book';

@Component({
   selector: 'app-data',
   templateUrl: './data.component.html'
})
export class DataComponent implements OnInit { 
   promiseBook: Promise<Book>
   constructor(private bookService: BookService) { }
   ngOnInit(): void {
	this.promiseBook = this.bookService.getBookSlowly();
   }
} 

AsyncPipe with Date

Find AsyncPipe to display current date and time.
time.component.html
<h3>AsyncPipe with Date</h3>

<div>{{ observableTime | async }} </div> <br/>

<div>{{ observableTime | async | date : 'mediumTime' }} </div> 
time.component.ts
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';

import { BookService } from './book.service';

@Component({
   selector: 'app-time',
   templateUrl: './time.component.html'
})
export class TimeComponent implements OnInit { 
   observableTime: Observable<string>
   constructor(private bookService: BookService) { }
   ngOnInit(): void {
        this.observableTime = this.bookService.getCurrentTime();
   }
}  

Application Component and Module

Find the application component and module.
app.component.ts
import { Component } from '@angular/core';

@Component({
   selector: 'app-root',
   template: `
		<app-observable></app-observable>
		<app-promise></app-promise>
		<app-data></app-data>
		<app-time></app-time>				
             `
})
export class AppComponent { 

} 
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { ObservableComponent } from './observable.component';
import { PromiseComponent } from './promise.component';
import { TimeComponent } from './time.component';
import { DataComponent } from './data.component';

//For InMemory testing
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { TestData } from './test-data';

@NgModule({
      imports: [
            BrowserModule,
            HttpClientModule,
            InMemoryWebApiModule.forRoot(TestData)
      ],
      declarations: [
            AppComponent,
            ObservableComponent,
            PromiseComponent,
            TimeComponent,
            DataComponent
      ],
      providers: [
      ],
      bootstrap: [
            AppComponent
      ]
})
export class AppModule { } 

Test Application

To run the application, find the steps.
1. Download source code using download link given below on this page.
2. Use downloaded src in your Angular CLI application. To install Angular CLI, find the link.
3. Install angular-in-memory-web-api@0.11.0
4. Run ng serve using command prompt.
5. Access the URL http://localhost:4200
Find the print screen of the output.
Angular Async Pipe Example

Reference

AsyncPipe

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI









©2023 concretepage.com | Privacy Policy | Contact Us