Home > Enterprise >  I want to show related data together from different APIs
I want to show related data together from different APIs

Time:03-18

I have two APIs:

component.ts

ngOnInit(): void {
       this.getQueryCountriesList().subscribe(arg => {
         this.countryDatas = arg;
       });
       this.getQueryNights().subscribe(obj => {
        this.nightDatas = obj;
      });
........
......
  getQueryCountriesList(){
    return this.http.get<any>(this.APIUrl   "/Visitor?tourType="  this.tourType  "&year="   this.selectedYear   "&month="   this.selectedMonth  "&gender="   this.selectedGender   "&age=" this.selectedAge);
  }
  getQueryNights(){
    return this.http.get<any>(this.APIUrl   "/Nights?tourType="  this.tourType  "&year="   this.selectedYear   "&month="   this.selectedMonth  "&gender="   this.selectedGender   "&age=" this.selectedAge);
  }

each data have same id, I want to show visits(from first API) and nights(second API) next to each other in table: component.html

<tr *ngFor="let country of countryDatas; let nights; of: nightDatas">
    <th [id]="country.countryId   '1'">{{ country.countryNameGe }}</th>
    <td [id]="country.countryId   '2'">{{ country.value }}</td>
    <td [id]="country.countryId   '3'">{{ nights.value }}</td>
</tr>

with the following code I get only nights or only visits in every column randomly

CodePudding user response:

Try to use Promise.all() to wait for the two api to return response, it can be helpful.

CodePudding user response:

You can use the rxJS's power. In this case, you can use forkJoin.

import { forkJoin } from 'rxjs';


ngOnInit(): void {
  forkJoin({
    countries: this.getQueryCountriesList(),
    nights: this.getQueryNights()
  }).subscribe(({countries, nights}) => {
      this.countryDatas = countries;
      this.nightDatas = nights;
  });

So, what is happing here? With forkJoin you are waiting that both observables from your API to be emitted, then emit an object that contains your data.

  • Related