Issue
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
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.
Answered By - Wasif Mustahid
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.