Angular 7/8 By Example with HttpClient, Async Pipe and Observables

Angular 7/8 By Example with HttpClient, Async Pipe and Observables

In this post we will give you information about Angular 7/8 By Example with HttpClient, Async Pipe and Observables. Hear we will give you detail about Angular 7/8 By Example with HttpClient, Async Pipe and ObservablesAnd how to use it also give you demo for it if it is necessary.

In this tutorial, we’ll learn by example how to send GET requests to REST API servers in your Angular 7/8 application using Httplient. We’ll also see how to use Angular services, RxJS Observables, models and the async pipe.

Note: Check out the how to use HttpClient with Angular 8 to build a news application from scratchin this tutorial or this tutorial for building a chat app.

Front end applications, built using frameworks like Angular communicate with backend servers through REST APIs (which are based on the HTTP protocol) using either the XMLHttpRequest interface or the fetch() API.

Angular HttpClient makes use of the XMLHttpRequest interface which also supports old browsers.

Throughout this tutorial, we are going to see practical examples of how to use HttpClient available from the@angular/common/http package, to make HTTP GET requests using the get() method.

We’ll also cover:

  • How to generate a fake and complete working REST API,
  • How to create Angular services,
  • How to subscribe to Observables,
  • How to use the async pipe in templates to iterate over Observable data.


Before getting started you need a few requirements. You need to have the following tools installed on your development machine:

  • Node.js and npm. You can install both from the official website.
  • Angular CLI 8 (You can install it from npm using: npm install -g @angular/cli)

You also need to create an Angular 8 project (these instructions are also completly valid for Angular 7).

In case, this is your first time using the Angular CLI, simply open your terminal and run the following command to generate a project:

$ ng new AngularHttpClientGetDemo

Please note that we are using HttpClient which is an improved version of HTTP Client API and available starting with Angular version 4.3.0-rc.0

Setting up HttpClient

The first step is to include HttpClientModule in your main application module. Open the src/app/app.module.ts file and update it accordingly:


That’s all, we are now ready to use the HttpClient in our project.

Setting up a Fake REST API

To work with HttpClient we need a REST API server, you can either use an external API service, create a real Rest API server or create a fake API using json-server. In this example we’ll use the last approach because it’s less time consuming.

So head over to your terminal and start by installing json-server from npm:

$ npm install -g json-server 

Next define your data in a db.json file:


Next, you can run a REST server using the following command:

$ json-server --watch db.json 

The HttpClient get() Method

The HttpClient get() method is designed to send HTTP GET requests. The syntax is as follows:


It takes a REST API endpoint and an optional options object and returns an Observable instance.

Now let’s take a real world example. Let’s presume you want to access the API endpoints we created above:

First you need to import HttpClient in your component.


Next you need to inject HttpClient via the component’s constructor


Next, add a method where you can call HttpClient.get(ENDPOINT_URL):


When called, this method will make a GET request to the /products endpoint then subscribe to the returned Observable. It will then log the array of products to the console.

Now let’s make a button to callthe get_products() method:

<button(click)="get_products()">GET /products</button>

Now, If you want to show the products on the component template.

First, add a products array:


Next change the get_products() method as follows:


We simply assing the returned products to the products array.

Next, use the ngFor directive in your component template to loop through the products array:

<ul><li*ngFor="let product of products">        -- id: {{}}        -- name: {{}}        -- cost: {{product.cost}}        -- quantity: {{product.quantity}}      </li></ul>

The async pipe and Observables

In our example, We can access the data returned by the get() method in two ways.

Subscribe to the returned Observable, i.e:


Or use the async pipe with the returned Observable and iterate directly over data in the template. Let’s see how in more details.

First, you need to create an Observable using the following:


Next, call the get() method and assign the result to productsObservable:


Finally, in your template:

<li*ngFor="let product of productsObservable | async">        -- id: {{}}        -- name: {{}}        -- cost: {{product.cost}}        -- quantity: {{product.quantity}}      </li>

We loop through the products using the Angular ngFor directive.

Using Angular Services

Using code that access data directly in your components is against the separation of concerns rule so let’s refactor our code to use an Angular service which makes HTTP GET requests then returns the result back to our component(s).

Using Angular CLI generate a new service:

$ ng generate service data 

Next move the data access code to this service. Open the src/app/data.service.ts file and update it accordingly:


Next, change the src/app/app.component.ts file as follows:

import{Component}from'@angular/core';import{Observable}from'rxjs';import{DataService}from'./data.service';/* .... */@Component({selector:'app-root',templateUrl:'./app.component.html',styleUrls:['./app.component.css']})exportclassAppComponent{privateproducts=[];privatefamilies=[];privatelocations=[];privatetransactions=[];privateproductsObservable:Observable<any[]>;constructor(privatedataService:DataService){this.productsObservable=this.dataService.get_products();this.dataService.get_families().subscribe((res:any[])=>{this.families=res;});this.dataService.get_locations().subscribe((res:any[])=>{console.log(res);this.locations=res;});this.dataService.get_transactions().subscribe((res:any[])=>{console.log(res);this.transactions=res;});}}

Instead of injecting HttpClient directly in our component we inject our data service and call its methods to make GET requests to our REST API server.

Creating Models

Now let’s further refactor our code to use models for products, families, locations and transactions.

In the root of Angular project, create these models:









Next update your the src/app/app.component.ts file to use the new models:


You can find the complete source code of this demo in GitHub.


We have seen a practical examples of how to use HttpClient get() to make HTTP GET requests to a REST API server in Angular 8, how to use the async pipe to subscribe to RxJS Observables in templates and finally how to use Angular services and model.

Hope this code and post will helped you for implement Angular 7/8 By Example with HttpClient, Async Pipe and Observables. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US