Performing Multiple HTTP Requests In Angular with ForkJoin One

To we are leaning RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using
observables that make it easier to compose asynchronous or callback-based code
. The RxJs is a part of forkJoin that use multiple HTTP requests at the same time call no need for extra function calls. forkJoin inside call all API is getting true than whole HTTP request data return.

Case in point

There are times when you need to make many HTTP requests (to the same or another server) and then wait for all of the HTTP answers before presenting the view.

When you need to wait for numerous HTTP requests to be resolved, the solution ‘forkJoin’ is the simplest.

‘forkJoin’ waits for each HTTP request to complete before combining all of the observables received by each HTTP call into a single observable array and returning that observable array.

import { Component, Inject, OnInit } from '@angular/core';
import { forkJoin } from 'rxjs';
@Component({
  selector: 'gpc-manage',
  templateUrl: './manage.component.html',
  styleUrls: ['./manage.component.scss'],
})
export class ManageComponent implements OnInit { 

 constructor(
    private companyService: CompanyService,
  ) {}

private onInitData(id: number) {
    forkJoin([
      this.companyService.returnNCCompanyList(),
      this.companyService.returnCompanyUserTypeList(id),
      // this.companyService.returnCompanyContactList(id),
    ]).subscribe((responce: any) => {
      if (responce) {
        if (responce[0] && responce[0].isSuccess) {
          this.ncCompanyList = responce[0].data;
        }
        if (responce[1] && responce[1].isSuccess) {
          this.dataTypeList = [...responce[1].data];
        }
        // if (responce[2] && responce[2].isSuccess) {
        //   this.emailInfo = [...responce[2].data];
        // }
      }
    });
  }

The above example displays three HTTP calls, but you can request as many HTTP calls as you need.

At the component level, as seen in the above code snippet, you subscribe to a single observable array and store the replies independently.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories