Angular 9 - how to merge 2 http.get into one Observable

Viewed 766

I use Angular 9 and want to merge 2 results from backend into one. My current method:

protected getDataSource(): Observable<AgentSummary> | Refresher<any, AgentSummary> {
  return this.groupSelector.selectedGroup$.pipe(e =>
    filter(Boolean),
    switchMap((group: SelectedGroup) => this.dashboardHttp.getAgentsStatus(group.id))
  );
}

I want to invoke additional http.get and merge it with

switchMap((group: SelectedGroup) => this.dashboardHttp.getAgentsStatus(group.id))

:

getRecoveryPoints(groupId: string): Observable<BackupSummary> {
  const headers: HttpHeaders = getHeaders(groupId);

    return this.http.get<BackupSummary>(`${this.env.URI}/backup/api/v1/dashboard/recovery-point`, {
    headers: headers,
  });
}

How to do that? I'm new in Angular so please be understanding for me:)

3 Answers

the rxjs function combineLatest should be what you need, you can read more about it here .

combineLatest([
  this.getDataSource(),
  this.getRecoveryPoints(groupId)
]).subscribe(([dataSource, recoveryPoints]) => {
  // do something
})

For combining two rest call you use combineLatest from rxjs

Example:

combineLatest([
   this.dashboardHttp.firstCall(),
   this.dashboardHttp.secondCall()
]).subscribe(([firstCallResponse, secondCallResponse]) => {
   console.log(firstCallResponse);
   console.log(secondCallResponse);
});

This way you can combine two call from backend.

You can combine http calls or any other kind of observables in many ways, my favorite is using combineLatest, here is the documentation:

let getDataSource$ = getDataSource();
let getRecoveryPoints$ = getRecoveryPoints();

combineLatest(getDataSource$, getRecoveryPoints$, 
  (dataSource, recoveryPoints) => ({dataSource, recoveryPoints})
    .subscribe( results => {
       let ( dataSource, recoveryPoints) = result;
         ... // do your stuff with the results
    })
Related