我想一起显示来自不同API的相关数据



我有两个API:

组件.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);
}

每个数据都有相同的id,我想在表中显示访问(来自第一个API(和夜晚(第二个API(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>

使用以下代码,我只能在每个专栏中随机获得夜晚或访问次数

尝试使用Promise.all((等待两个api返回响应,这可能会有所帮助。

您可以使用rxJS的功能。在这种情况下,可以使用forkJoin

import { forkJoin } from 'rxjs';

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

那么,这里发生了什么?使用forkJoin,您正在等待API中的两个可观察性都被发射,然后发射包含数据的对象。

您可以使用rxjs combineLatest运算符,该运算符将等待两个可观测值至少发出一个值。从那里,构建包含两个值的数组:

import { combineLatest } from 'rxjs';

ngOnInit(): void {
queryCountriesList$ = this.getQueryCountriesList();
queryNights$ = this.getQueryNights();
combineLatest([queryCountriesList$,queryNights$])
.subscribe(([queryCountriesList, queryNights]) => 
{
// create your object here 
}
}

使用RxJS运算符中的combineLatest。参观https://rxjs.dev/api/index/function/combineLatest

import { combineLatest, of } from 'rxjs';
import { map } from 'rxjs/operators';
const weight = of(70, 72, 76, 79, 75);
const height = of(1.76, 1.77, 1.78);
const bmi = combineLatest([weight, height]).pipe(
map(([w, h]) => w / (h * h)),
);
bmi.subscribe(x => console.log('BMI is ' + x));
// With output to console:
// BMI is 24.212293388429753
// BMI is 23.93948099205209
// BMI is 23.671253629592222

在您的情况下:

const combined = combineLatest([
getQueryCountriesList(),
getQueryNights(),
]).pipe(
map(([countries, nights]) => {
// your logic to combine object, make sure to return the final value
})
);
combined.subscribe((x) => console.log("Final result is " + x));

最新更新