A comprehensive step by step tutorial on Multiple HTTP using Angular 8 RxJS forkJoin operator including an example

One of the RxJS operators is the forkJoin which handles a group of Observable by detecting the final emitted value of each. So, we are using this RxJS operator for multiple HTTP requests or RESTful API request of the Angular 8 Web Application.

The main purpose is to use one Loading spinner process for multiple RESTful API requests of the Angular 8 Web Application. We will put the multiple HTTP or RESTful API request in the Angular 8 Service. So, the Loading spinner will load and stop from the Angular 8 Controller and displayed in the Angular 8 Template.

We will display the weathers of the 4 cities at one time on one page. We use the Meta weather free API for it. You can see each API endpoint at the steps of this tutorial.

The following tools, framework, libraries, and modules are required for this tutorial:

Before moving to the steps, make sure you have installed the latest Node.js. To check it, type this command in the terminal or Node.js command line.

node -v 
v10.15.1 
npm -v 
6.9.0

Install Angular CLI and Create Angular 8 Application

We will create an Angular 8 application using Angular CLI from the terminal or command line. For that, we have to install a new Angular CLI or update an existing Angular CLI using this command from the terminal or command line.

sudo npm install -g @angular/cli

You can skip sudo if you are using Command-Line or if your terminal allowed without sudo. To check the existing version of Angular CLI, type this command.

ng version

 

   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|

  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |

 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |

/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|

               |___/

 

Angular CLI: 8.1.2

Node: 10.15.1

OS: darwin x64

Angular:

...

 

Package                      Version

------------------------------------------------------

@angular-devkit/architect    0.801.2

@angular-devkit/core         8.1.2

@angular-devkit/schematics   8.1.2

@schematics/angular          8.1.2

@schematics/update           0.801.2

rxjs                         6.4.0


We are using above Angular 8 and RxJS version. Next, we have to create a new Angular 8 application using this command.

ng new angular-forkjoin

Answer the question the same as below.

? Would you like to add Angular routing? No
? Which stylesheet format would you like to use? SCSS   [ https://sass-lang.com/documentation/synta
x#scss

Next, go to the newly created Angular 8 application folder then run the Angular 8 application for the first time.

cd ./angular-forkjoin 
ng serve

Now, open the browser then go to [http://localhost;4200/](http://localhost;4200/ "http://localhost;4200/") and you will see the standard Angular 8 page.

Create an Angular 8 Service

The main feature that we mention in the title of this tutorial is using the RxJS forkJoin to call multiple RESTful API at one call. We do that in the Angular 8 Service. For that, generate a new Angular 8 service using Angular CLI.

ng g service rest-api

Next, open and edit src/app/rest-api.service.ts then add these imports.

import { Observable, of, throwError } from 'rxjs'; 
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; 
import { forkJoin } from 'rxjs';

Add this line after the imports lines as a constant variable of the RESTful API endpoint that we will use.

const apiUrl = 'http://localhost:1337/www.metaweather.com/api/location/';

As you see, we are using the localhost:1337 in the front of the Meta weather URL because the RESTful API, not CORS enabled. For that, we have to install the Corsproxy-HTTPS using this command.

sudo npm install -g corsproxy-https

Next, inject HttpClient module to the constructor.

constructor(private http: HttpClient) { }

Next, create multiple RESTful API calls at once in a function using the above API URL with a different parameter value that describe the code of the city.

getData(): Observable<any> {
  const response1 = this.http.get(apiUrl + '44418/');
  const response2 = this.http.get(apiUrl + '2459115/');
  const response3 = this.http.get(apiUrl + '28743736/');
  const response4 = this.http.get(apiUrl + '1940345/');
  return forkJoin([response1, response2, response3, response4]);
}


As you see the forkJoin combine the 4 API calls together at the end of the function. The Angular 8 HttpClient module should register in the Angular 8 main module. For that, open and edit src/app/app.module.ts then add this import.

import { HttpClientModule } from '@angular/common/http';

Then add this module to the @NgModule imports.

 imports: [
  BrowserModule,
  HttpClientModule
],


Display Multiple Details of Data using Angular 8 Material

Now, we have to display the 4 different API calls responses to the Angular 8 page using Angular 8 Material. First, we have to add Angular 8 Material using this Angular CLI.

ng add @angular/material

Answer all question that shows during the installation as below.

? Choose a prebuilt theme name, or "custom" for a custom theme: Indigo/Pink        [ Preview: https
://material.angular.io?theme=indigo-pink ]
? Set up HammerJS for gesture recognition? Yes
? Set up browser animations for Angular Material? Yes


We will register all required Angular 8 Material components or modules to src/app/app.module.ts. Open and edit that file then add these imports.

 import {
  MatInputModule,
  MatPaginatorModule,
  MatProgressSpinnerModule,
  MatSortModule,
  MatTableModule,
  MatIconModule,
  MatButtonModule,
  MatCardModule,
  MatFormFieldModule } from '@angular/material';


Register that imported modules to the @NgModule imports.

 imports: [
  ...
  BrowserAnimationsModule,
  MatInputModule,
  MatTableModule,
  MatPaginatorModule,
  MatSortModule,
  MatProgressSpinnerModule,
  MatIconModule,
  MatButtonModule,
  MatCardModule,
  MatFormFieldModule
],

Next, open and edit src/app/app.component.ts then add this import.

import { RestApiService } from './rest-api.service';

Add these lines of variables after the title variable.

data1: any = {}; 
data2: any = {}; 
data3: any = {}; 
data4: any = {}; 
isLoadingResults = true;

Add the constructor that inject the REST API service and call the get data function.

constructor(private api: RestApiService) {
  this.getData();
}

Add a function to get data from the REST API service.

getData() {
  this.api.getData()
    .subscribe(res => {
      console.log(res);
      this.data1 = res[0];
      this.data2 = res[1];
      this.data3 = res[2];
      this.data4 = res[3];
      this.isLoadingResults = false;
    }, err => {
      console.log(err);
      this.isLoadingResults = false;
    });
}

Next, open and edit src/app/app.component.html then replace all exisiting HTML tags with these tags.

 <div class="example-container mat-elevation-z8">
  <div class="example-loading-shade"
       *ngIf="isLoadingResults">
    <mat-spinner *ngIf="isLoadingResults"></mat-spinner>
  </div>
  <mat-card class="example-card">
    <mat-card-header>
      <mat-card-title><h2>{{data1.title}}</h2></mat-card-title>
      <mat-card-subtitle>Sunrise at {{data1.sun_rise | date: 'HH:mm:ss'}}, Sunset at {{data1.sun_set | date: 'HH:mm:ss'}}</mat-card-subtitle>
    </mat-card-header>
    <mat-card-content>
      <ul>
        <li *ngFor="let source of data1.sources"><a href="{{source.url}}" target="_blank">{{source.title}}</a></li>
      </ul>
    </mat-card-content>
  </mat-card>
  <mat-card class="example-card">
    <mat-card-header>
      <mat-card-title><h2>{{data2.title}}</h2></mat-card-title>
      <mat-card-subtitle>Sunrise at {{data2.sun_rise | date: 'HH:mm:ss'}}, Sunset at {{data2.sun_set | date: 'HH:mm:ss'}}</mat-card-subtitle>
    </mat-card-header>
    <mat-card-content>
      <ul>
        <li *ngFor="let source of data2.sources"><a href="{{source.url}}" target="_blank">{{source.title}}</a></li>
      </ul>
    </mat-card-content>
  </mat-card>
  <mat-card class="example-card">
    <mat-card-header>
      <mat-card-title><h2>{{data3.title}}</h2></mat-card-title>
      <mat-card-subtitle>Sunrise at {{data3.sun_rise | date: 'HH:mm:ss'}}, Sunset at {{data3.sun_set | date: 'HH:mm:ss'}}</mat-card-subtitle>
    </mat-card-header>
    <mat-card-content>
      <ul>
        <li *ngFor="let source of data3.sources"><a href="{{source.url}}" target="_blank">{{source.title}}</a></li>
      </ul>
    </mat-card-content>
  </mat-card>
  <mat-card class="example-card">
      <mat-card-header>
        <mat-card-title><h2>{{data4.title}}</h2></mat-card-title>
        <mat-card-subtitle>Sunrise at {{data4.sun_rise | date: 'HH:mm:ss'}}, Sunset at {{data4.sun_set | date: 'HH:mm:ss'}}</mat-card-subtitle>
      </mat-card-header>
      <mat-card-content>
        <ul>
          <li *ngFor="let source of data4.sources"><a href="{{source.url}}" target="_blank">{{source.title}}</a></li>
        </ul>
      </mat-card-content>
    </mat-card>
</div>

Finally, open and edit src/app/app.component.scss then add these lines of SCSS codes to give an adjustment for the styles.

 .example-container {
  position: relative;
  padding: 5px;
  background-color: aqua;
}
 
.example-loading-shade {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 56px;
  right: 0;
  background: rgba(0, 0, 0, 0.15);
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}
 
.example-card {
  margin: 5px;
  padding-bottom: 40px;
}

Run and Test the Complete Angular 8 RxJS Example

As you see in the previous steps, we already installing Corsproxy-HTTPS Node module. So, open the new Terminal/Command Line tab then run that Corsproxy before running the Angular 8 Application.

corsproxy

Back to the current Terminal tab, type this command to run the Angular 8 application.

ng serve

In the browser go to [http://localhost:4200/](http://localhost:4200/ "http://localhost:4200/") then you will see the single page like below.

That it’s, the Angular 8 RxJS Multiple HTTP Request using the forkJoin Example. You can find the full source code from our GitHub.

#angular #web-development #node-js

RxJS tutorial - Multiple HTTP requests in Angular 8 with forkJoin
82.55 GEEK