How to Perform Multiple HTTP Requests in Angular

Learn how to fetch data from multiple HTTP requests simultaneously in Angular applications.

Photo by Miguel Á. Padriñán: https://www.pexels.com/photo/close-up-shot-of-keyboard-buttons-2882570/

In this post, I will show you an approach for retrieving data using multiple HTTP requests. This is a scenario that you will undoubtedly bump into while building real-world applications.

Dependencies

The first thing you need to fetch data using HTTP is an instance of HttpClient. So, we must declare it as a constructor parameter and ensure that we import the HttpClientModule.

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { forkJoin } from 'rxjs';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  resultMessage = 'Loading';

  // Declare dependency on HttpClient
  constructor(private httpClient: HttpClient) {}

  ngOnInit(): void {
    // to be added
  }
}

First approach

Once we have this requirement, we can get on with the concrete implementation. We will fetch country and city information from two JSON files: “assets/countries.json” and “assets/cities.json”. The code will be written in the ngOnInit method.

ngOnInit(): void {
  this.httpClient.get<[]>('assets/countries.json')
    .subscribe((countries) => {
      // first call
      this.httpClient.get<[]>('assets/cities.json')
      .subscribe((cities) => {
        // second call => all data loaded
        console.log(countries);
        console.log(cities);
        this.resultMessage = `Fetched ${countries.length} and ${cities.length} cities sequentially`;
    });
});

This approach looks simple enough, and it works, but it has two major downfalls:

  • We end up with a lot of nesting. Each HTTP call creates another level of nesting in our code, which will become hard to reason about.

  • The requests are made sequentially. First, we retrieve the country data and then the city data. Each HTTP request will wait until the ones before it is completed.

Executing multiple HTTP requests in parallel using forkJoin

A better approach is to use the forkJoin operator from RxJs and fetch the data in parallel.

import { forkJoin } from 'rxjs';
ngOnInit(): void {
  const $countries = this.httpClient.get<[]>('assets/countries.json');
  const $cities = this.httpClient.get<[]>('assets/cities.json');

  forkJoin([$countries, $cities]).subscribe(([countries, cities]) => {
    // All data available
    console.log(countries);
    console.log(cities);
    this.resultMessage = `Fetched ${countries.length} and ${cities.length} cities`;
  });
}

Using this approach, we can combine the responses from multiple HTTP requests. The requests are executed in parallel, and forkJoin will wait until they all emit. Also, notice that the code is easier to read. All the logic is happening in a single block of code.

Previous
Previous

How to Create a Custom MongoDB Spring Data Repository

Next
Next

The Best Way to Create Functions in JavaScript