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
Try to use Promise.all() to wait for the two api to return response, it can be helpful.
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.
You can use the rxjs combineLatest operator that will wait for both observables to emit at least one value. And from there, build your array that contains both values:
import { combineLatest } from 'rxjs';
ngOnInit(): void {
queryCountriesList$ = this.getQueryCountriesList();
queryNights$ = this.getQueryNights();
combineLatest([queryCountriesList$,queryNights$])
.subscribe(([queryCountriesList, queryNights]) =>
{
// create your object here
}
}