DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Difference Between Observable and Promise in Angular 8
  • How to Create a Nested Grid Using Angular 8
  • How to Work With a Text Editor in an Angular 8 Application
  • Implementing Micro Frontends in Angular: Step-By-Step Guide

Trending

  • AI-Based Threat Detection in Cloud Security
  • How to Practice TDD With Kotlin
  • Memory Leak Due to Time-Taking finalize() Method
  • Docker Model Runner: Streamlining AI Deployment for Developers
  1. DZone
  2. Data Engineering
  3. Data
  4. How To Use Async Pipe in Angular 8

How To Use Async Pipe in Angular 8

By 
Siddharth Gajbhiye user avatar
Siddharth Gajbhiye
·
Apr. 20, 20 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
63.0K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction 

In this article, we are going to learn how to use an Async Pipe in Angular applications. 

What Is Async Pipe?

Async Pipe is an impure pipe that automatically subscribes to an observable to emit the latest values. It not only subscribes to an observable, but it also subscribes to a promise and calls the then method. When the components get destroyed, it automatically unsubscribes them to reduce memory leaks.

Advantages of Async Pipe

  1. Async Pipe makes the rendering of data from observable and promise easier.
  2. For promises, it automatically calls the then method.
  3. For observables, it automatically calls subscribe and unsubscribe.

Prerequisites

  • Basic knowledge of Angular.
  • Visual Studio Code must be installed.
  • Angular CLI must be installed.
  • Node JS must be installed.

Step 1

Let's create a new Angular project, using the following NPM command:

TypeScript
xxxxxxxxxx
1
 
1
ng new asyncPipe

 

Step 2

Now, let's create a new component by using the following command:

TypeScript
xxxxxxxxxx
1
 
1
ng g c async-pipe-example

 

Step 3

Now, open the async-pipe-example.component.html file and add the following code in the file:

HTML
xxxxxxxxxx
1
44
 
1
<div class="card">    
2
  <div class="card-body pb-0">    
3
    <h4 style="text-align: center;">{{SampleMessage}}</h4>    
4
    <div class="row">    
5
      <div class="col-12 col-md-12">    
6
        <div class="card">    
7
    
8
          <div class="card-body position-relative">    
9
            <div class="table-responsive cnstr-record product-tbl">    
10
              <table class="table table-bordered heading-hvr">    
11
                <thead>    
12
                  <tr>    
13
                     
14
                    <th width="50">Art.No    
15
                    </th>    
16
                    <th>Brand</th>    
17
                    <th>    
18
                      Price/Unit</th>    
19
                    <th>Provider</th>    
20
                    <th>P. Art. N</th>    
21
                    <th>S. A/C</th>    
22
               
23
                  </tr>    
24
                </thead>    
25
    
26
                <tbody *ngFor="let product of products$ | async">    
27
                  <tr>    
28
                    <td align="center">{{product.ArtNo}}</td>    
29
                    <td>{{product.Brand}}</td>    
30
                    <td>{{product.Price }}</td>    
31
                    <td>{{product.Provider}}</td>    
32
                    <td>{{product.ProviderArtNo}}</td>    
33
                    <td>{{product.SalesAccount}}</td>    
34
                 
35
                  </tr>    
36
                </tbody>    
37
              </table>    
38
            </div>    
39
          </div>    
40
        </div>    
41
      </div>    
42
    </div>    
43
  </div>    
44
</div>  


Here, in the following code, we can see how to apply async pipe with our structural directive, *ngFor.

HTML
xxxxxxxxxx
1
 
1
<tbody *ngFor="let product of products$ | async">    


Step 4

Now, open the async-pipe-example.component.ts file and add the following code in the file:

TypeScript
xxxxxxxxxx
1
35
 
1
import { Component, OnInit } from '@angular/core';    
2
import { ProductsService } from '../product.service';    
3
import { Observable } from 'rxjs';    
4
    
5
@Component({    
6
  selector: 'app-async-pipe-example',    
7
  templateUrl: './async-pipe-example.component.html',    
8
  styleUrls: ['./async-pipe-example.component.css']    
9
})    
10
export class AsyncPipeExampleComponent implements OnInit {    
11
  products = [];    
12
  products$:Observable<any>;    
13
  SampleMessage="Example of Angular Async Pipe";    
14
    
15
  constructor(private _productService:ProductsService) { }    
16
    
17
  ngOnInit() {    
18
    //this.getProductsUsingSubscribeMethod();    
19
    this.getProductsUsingAsyncPipe();    
20
  }    
21
    
22
  public getProductsUsingSubscribeMethod() {    
23
    this.SampleMessage="Example of Angular Subscribe Method";    
24
    this._productService.getAllProducts().subscribe((data: any) => {    
25
      this.products =data;    
26
      console.log(data);    
27
    })    
28
  }    
29
    
30
  public getProductsUsingAsyncPipe() {    
31
    this.SampleMessage="Example of Angular Async Pipe";    
32
    this.products$ =this._productService.getAllProducts();    
33
  }    
34
    
35
}  


Here, in the following code, we are using observables of any type. To get the asynchronous flow data, we can use the subscribe method to subscribe to the observables, or we can simply use async pipe, which automatically subscribes to an observable and returns the latest value. It also unsubscribes automatically to avoid memory leaks.

TypeScript
xxxxxxxxxx
1
 
1
public getProductsUsingAsyncPipe() {      
2
  this.SampleMessage="Example of Angular Async Pipe";      
3
  this.products$ =this._productService.getAllProducts();      
4
}  


Step 5

Now, open the product.service.ts file and add the following code:

TypeScript
xxxxxxxxxx
1
14
 
1
import { Injectable } from '@angular/core';    
2
import { HttpClient } from '@angular/common/http';    
3
  
4
@Injectable()       
5
export class ProductsService {      
6
    private url = '';    
7
    private baseUrl = "http://localhost:49661/";//Replace it with your http address and port      
8
    constructor(public http: HttpClient) {    
9
    }      
10
    getAllProducts() {    
11
        this.url = this.baseUrl+'api/Product/getAllProducts';    
12
        return this.http.get<any[]>(this.url);    
13
    }      
14
}  


Web API: Create an ASP.NET Application

Follow these steps to create an ASP.NET application. 

Step 1

In Visual Studio 2019, click on File -> New -> Project.

Creating a new ASP.NET project
Creating a new ASP.NET project

Step 2

Choose the Create option and select ASP.NET web application.

Creating a new ASP.NET application
Creating a new ASP.NET app

Step 3

Select Web API and click OK.

Creating Web API
Adding Web API

Step 4

Now, right-click on the controller and then add a new item. 

Adding a new item
Adding a new item

Step 5

Choose Ado.net Entity Data Model and then click on Add. 

Creating a new data model
Creating a new data model

Step 6

The next step focuses on the EF Designer. Just click on Next. 

Selecting EF Designer
Selecting EF Designer

Step 7

 A new pop-up will show. Click on Next. If yours isn't established, then click on New Connection.

Choosing connection
Choosing connection

Step 8

Copy your database connection server name and paste it in the server name textbox. You will see all the databases. Select your database and click on OK.

Selecting correct database
Selecting correct database

Step 9

The next popup will show. Paste your database server name, choose the database, and test for the connection. Then, click Next. Here, in the new screen, select your tables and store the procedure. Then, click on Finish. 

Choosing database objects and store
Choosing database objects and store

Our next step is to right-click on the controllers folder, and add a new controller. Name it as "Product controller" and add the following namespace in the student controller.

Here is the complete code for getting all the product data and their nested product information data. 

Complete Product controller code

C#
xxxxxxxxxx
1
15
 
1
using System.Linq;  
2
using System.Web.Http;  
3
using CompanyDetails.Models;  
4
namespace CompanyDetails.Controllers {  
5
    [RoutePrefix("api/Company")]  
6
    public class CompanyController: ApiController {  
7
        CompanyEntities2 DB = new CompanyEntities2();  
8
        [HttpGet]  
9
        [Route("getAllProducts")]  
10
        public object getAllProducts(string countrycode) {  
11
            var productDetails = DB.USP_GetAllProducts().ToList();  
12
            return productDetails;  
13
        }  
14
    }  
15
}  


Now, it's time to enable CORS. Go to Tools, open NuGet Package Manager, search for CORS, and install the "Microsoft.Asp.Net.WebApi.Cors" package. 

If you are running your frontend application in a different port and your server is running in another port, then to avoid a Cross-Origin-Resource-Sharing issue you have to add small code in webapiconfig.cs file.

Open Webapiconfig.cs and add the following lines.

C#
xxxxxxxxxx
1
 
1
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");  
2
config.EnableCors(cors);  


Backend

Here, we will do back end related code using SQL Server. The very first step is to create a database.

Create Database

Let’s create a database on your local SQL Server. I hope you have installed SQL Server 2017 on your machine (you can use SQL Server 2008, 2012, or 2016, as well). 

Step 1

Create a database product:

SQL
xxxxxxxxxx
1
 
1
create database product  


Step 2

Create a product table using the following code:

SQL
xxxxxxxxxx
1
19
 
1
USE [Product]  
2
GO  
3
/****** Object: Table [dbo].[Product] Script Date: 12/18/2019 10:23:19 PM ******/  
4
SET ANSI_NULLS ON  
5
GO  
6
SET QUOTED_IDENTIFIER ON  
7
GO  
8
CREATE TABLE [dbo].[Product](  
9
[ProductId] [int] IDENTITY(1,1) NOT NULL,  
10
[ArtNo] [nvarchar](50) NULL,  
11
[Provider] [nvarchar](50) NULL,  
12
[ProviderArtNo] [nvarchar](50) NULL,  
13
[Brand] [nvarchar](50) NULL,  
14
CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED  
15
(  
16
[ProductId] ASC  
17
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
18
) ON [PRIMARY]  
19
GO  


Make product ID the primary key. Now, it's time to add some store procedures.

Step 4

All you have to do is paste the following code in a new query:

SQL
x
12
 
1
USE [Product]  
2
GO  
3
/****** Object: StoredProcedure [dbo].[USP_GetAllProducts] Script Date: 12/18/2019 10:24:35 PM ******/  
4
SET ANSI_NULLS ON  
5
GO  
6
SET QUOTED_IDENTIFIER ON  
7
GO  
8
ALTER Proc [dbo].[USP_GetAllProducts]  
9
As  
10
Begin  
11
Select p.*,pci.Price,pci.BuyAccount,pci.SalesAccount from [Product] p  
12
End  


With this step, we have successfully completed our frontend, web API, and backend coding. Now, it's time to run the project by using npm start or  ng serve and check the output.

Conclusion

In this article, we have learned how to use an Async Pipe in Angular 8 Application. 

Please give your valuable feedback/comments/questions about this article. Please let me know if you liked and understood this article and how I could improve it.

Database connection AngularJS Web API application

Opinions expressed by DZone contributors are their own.

Related

  • Difference Between Observable and Promise in Angular 8
  • How to Create a Nested Grid Using Angular 8
  • How to Work With a Text Editor in an Angular 8 Application
  • Implementing Micro Frontends in Angular: Step-By-Step Guide

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!