Home  >  Angular 4

Angular 2 Async Pipe Example

By Arvind Rai, April 10, 2017
On this page we will provide angular 2 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 example.
1. Angular 4.0.0
2. TypeScript 2.2.0
3. Node.js 6.10.1
4. Angular CLI 1.0.0
5. Angular Compiler CLI 4.0.0

Create Service using @Injectable()

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 { Http, Response } from '@angular/http';
import { Observable, Subscriber } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

import { Book } from './book';

@Injectable()
export class BookService {
    url = "http://localhost:4200/data/books.json";
    constructor(private http:Http) { }
    //Returns Observable<Book[]>
    getBooksWithObservable(): Observable<Book[]> {
        return this.http.get(this.url).map((res: Response) => res.json());
    }
    //Returns Promise<Book[]>
    getBooksWithPromise(): Promise<Book[]> {
        return this.http.get(this.url).toPromise().then((res: Response) => res.json());
    }
    //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.
@Injectable(): This decorator is used to make a service available for injection by injector.
Http: Angular service to handle server communication.
http.get() : This method is used to access HTTP URL using HTTP GET method.
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.
map(): This is a RxJS operator that extracts response object from response data.
toPromise(): This is a RxJS operator that converts Observable into Promise.
Response : It represents a response to a request.
Response. json(): It returns a Promise that resolves with a JSON object.
setInterval() : Sets a time interval after which it re-executes.
setTimeout(): Sets a timeout after which method executes.

Find dummy JSON file and class that will hold data.
books.json
[
  {"id": 1, "name": "Core Java"},
  {"id": 2, "name": "Angular 2"},
  {"id": 3, "name": "Hibernate"},
  {"id": 4, "name": "Spring"}
]  
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 { HttpModule } from '@angular/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';
import { BookService } from './book.service';

@NgModule({
  imports: [     
        BrowserModule,
	HttpModule
  ],
  declarations: [
        AppComponent,
	ObservableComponent,
	PromiseComponent,
	TimeComponent,
	DataComponent
  ],
  providers: [
        BookService
  ],
  bootstrap: [
        AppComponent
  ]
})
export class AppModule { } 

Test Application

To test the application, find following steps.
1.: Download source code. We will get src and data folder.
2.: In our angular CLI application, place src folder and parallel to src folder, place data folder. Now we can access JSON data using following URL.
http://localhost:4200/data/books.json 
3.: Now run the application. Find the print screen of the output.
Angular 2 Async Pipe Example

Reference

AsyncPipe

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS








Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us