• Angular
  • React
  • NextJs
  • Sass

Angular Async Pipe Example

By Webrecto, 23 July 2023

Angular's async pipe is a powerful tool for dealing with asynchronous operations in our templates. It is a special type of pipe that allows you to automatically subscribe to a Promise or Observable type of data and return the latest value. We can use async pipe directly in directives such as NgFor, NgIf, and NgSwitch. The async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribe automatically.

Async pipes are a way to write display-value transformations that you can declare in HTML template.

Syntax of Async Pipe

{{  expression | async }}

The use of Async pipe

1 - Async pipe subscribes to a promise or an observable and returns the last emitted value.

2 - Whenever a new value is emitted, it marks the component to be checked, which means Angular will run a change detector for that component in the next cycle.

3 - It unsubscribes from the observable when the component gets destroyed.

Complete Example

In this example, I will create employee details in JSON format in the employee service file and will use HTTP URL, and I will use NgFor directive to iterate the data. I will display employee data using an async pipe.

Create a Service for Employee

Let's start with creating an employee details interface and a service. I created one interface for employee details and initialized all variable types. The interface is a way to define a contract on a function with respect to the argument and its type.

export interface IEmployee {
	id: string;
	name: string;
	employee_code: string;
	department: string;
	shift: string;
	manager_name: string
}

employee.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Subscriber } from 'rxjs';
import {IEmployee} from '../interface/employee';

@Injectable({
 providedIn: 'root'
})

export class EmployeeService {

	url = "api/employees";

	constructor(private http: HttpClient) { }
	getEmployeeWithObservable(): Observable<IEmployee[]> {
	return this.http.get(this.url);

	}
}

In the service code I am using Observable.
Observable: Observable is provided by the RxJS library. Observable handle a variety of common asynchronous operations in the application and return multiple values over time. It is commonly used in angular applications for handling events.

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 employee = [
            {
                id: 1,
                name: 'John',
                employee_code: 'TI2456',
                department: 'Development',
                shift: 'Morning',
                manager_name: 'Robert'
            },
            {
                id: 2,
                name: 'Michal Man',
                employee_code: 'TI2457',
                department: 'Development',
                shift: 'Morning',
                manager_name: 'Robert'
            },
            {
                id: 3,
                name: 'Rajeev Pandey',
                employee_code: 'TI2458',
                department: 'Tester',
                shift: 'Evening',
                manager_name: 'Jocylene'
            },
            {
                id: 4,
                name: 'Amit Kumar Singh',
                employee_code: 'TI2460',
                department: 'Tester',
                shift: 'Evening',
                manager_name: 'Jocylene'
            }
        ];
        return { employees: employee };
    }
} 

In the above example, I am using angular-in-memory-web-api. The angular-in-memory-web-api module provides an in-memory data store where we can create and fetch data. In the Angular service, we implement the created method of the InMemoryDbService interface, which creates an object in memory that represents our database.

AsyncPipe with Observable using NgFor

In this example, we will use AsyncPipe with Observable and iterate data with the help of the NgFor directive.

observable.component.html

<h3>AsyncPipe with Observable using NgFor</h3>
<table>
    <tr>
        <th>Employee Code</th>
        <th>Emplyee Name</th>
        <th>Department</th>
        <th>Manager name</th>
    </tr>
    <tr *ngFor="let employee of observableEmployee | async" >
       <td>{{employee.employee_code}}</td>
       <td>{{employee.name}}</td>
       <td>{{employee.department}}</td>
       <td>{{employee.manager_name}}</td>
    </tr>
</table>

observable.component.ts

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

import { EmployeeService } from './service/employee.service';
import { IEmployee } from './interface/employee';

@Component({
   selector: 'app-observable',
   templateUrl: './observable.component.html'
})
export class ObservableComponent implements OnInit { 

    observableEmployee: any = "";

    constructor(private employeeService: EmployeeService) { }
    ngOnInit(): void {
        this.observableEmployee = this.employeeService.getEmployeeWithObservable();
   }
} 

Application Component and Module

In this article app.module is a shared module and is used to initialize all components, pipe, and service files. The App component is responsible for rendering a view and handling user interactions with the view.

app.component.ts

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

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

app.module.ts

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ObservableComponent } from './observable.component';
//For InMemory testing
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { TestData } from './service/test-data';

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

Find the print screen of the output.

Angular Async Pipe Example

Reference

Download Source Code