RxJS tutorial - Multiple HTTP requests in Angular 8 with forkJoin

RxJS tutorial - Multiple HTTP requests in Angular 8 with forkJoin

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

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 JS Development Company

If you’re finding AngularJS Development Company for consultation or Development, your search ends here at Data EximIT 

🔗 Click here to know more: AngularJS Development




Top Web Application Developer

Top Web Application Developer

You can also contact a web application development company for your business but then why not to contact the best web application development company that can turn up your business and customer satisfaction ratio to sky touching heights.

Not long-ago internet came into existence and the world has never been the same ever since. The Internet made sure that people and business do evolve at a faster rate than ever and was never merciful to the slow ones. Because of this competition and availability of any business with few clicks made India one of the hubs as IT center. This trend of constantly updating has given rise to smartphones, smart machines, wearable gadgets and a lot more is yet to come in the upcoming years. In such time it is always a good idea to hire Web App Developer from India at your service. They are expert in developing not only websites but web applications as well.

We at HireFullStackDeveloperIndia, have a huge team of experienced developers that have grasped over different domains in front and back end development. You can hire web app developers in India from us with many advantages that you won’t get anywhere else in the industry.

Here is why we are the best option if you are looking forward to hiring web app developers in India:

  • Flexible hiring models available, as per your convenience and requirement
  • Maximum ROI, compared to any other company or team of developers.
  • We provide you with Source code Authorization meaning code written for you belong only to you. It cannot be used or copied anywhere else.
  • All of our developers are sound with agile development methodology, so you will be in a constant loop of suggestions, ideas, trends, and updates about your project.
  • Our developers are good with creating custom web applications as well; it guarantees you a better product without any compromise of non-existing functionalities.
  • You can save huge costing on infrastructure by utilizing our hire web app developer in India program.
  • Your hired developer or team will be easily accessible to your preferred mode of communication.
  • You get to exercise complete control over your team or individual that you hire.
  • We believe in Integrity and Transparency.
  • Our developers are highly creative and motivated to deliver excellence.


HireFullStackDeveloperIndia is a Web Application Development Company in India that is known worldwide for our Innovative guaranteed solutions. You can inquire with us about your project and we will be providing you multiple suitable developers that are the best fit for your requirements. You can evaluate them and select one or multiple whosoever deems fit to you. After this, all you have to do is provide your valuable input to the resource through sprint base project development until you get delivery of your project.

Our engagement model will also allow you to get our development team to your site location and proceed with development from your premises.