Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to combine multiple HTTP calls in Angular using RxJS?

I’m trying to make multiple HTTP calls simultaneously in my Angular service and I want to combine the responses into a single object. How can I do this using RxJS?

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
   providedIn: 'root'
})
export class DataService {
   constructor(private http: HttpClient) {}

   getData1(): Observable<any> {
     return this.http.get('https://api.example.com/data1');
   }

   getData2(): Observable<any> {
     return this.http.get('https://api.example.com/data2');
   }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

By using forkjoin

getCombinedData(): Observable<any> {
     return forkJoin([this.getData1(), this.getData2()]);
   }
combineData() {
    this.dataService.getCombinedData().subscribe((responses) => {
      const [data1, data2] = responses;
    });

By using concatMap: Use concatMap to make sequential HTTP calls and combine their results. This is useful when you want to ensure that the calls are made one after another.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading