如何在需要 2 个 API 调用的 Angular/rxjs 中加载我的对象 [英] How can I load my object in Angular/rxjs that requires 2 API calls
问题描述
我使用的是 Angular 6.
I am using Angular 6.
我有以下课程:
export class MyItem{
id: string;
name: string;
gizmo: Gizmo;
};
export class Gizmo{
id: string;
name: string;
color: string;
};
我必须进行 2 个 API 调用.
1 - 获取 MyItems 数组.
2 - 获取给定 MyItem 的 Gizmo.
I have to make 2 API calls.
1 - To get the array of MyItems.
2 - To get the gizmo of a given MyItem.
我已经试过了:
this.myItemService.get<MyItem[]>(
new FindParameters({ name: name })
).pipe(tap(z => {
z.forEach(function (item) {
this.gizmoService.get(item.id)
.subscribe(z => {
item.gizmo = z;
});
});
}))
.subscribe(x => this.totalCount = x.length);
但是 gizmoService 似乎不在函数内的范围内.(如果我把它拉出来服务很好)
However the gizmoService appears to not be in scope inside the function. (If I pull it out the service is fine)
那么如何加载需要 2 个单独 API 调用的对象?
So how can I load my object that will require 2 separate API calls?
推荐答案
将 .subscribe()
调用到 .subscribe()
中是一种反模式,必须不惜一切代价避免.你应该做的是将你的 api 调用合并到一个单一的 observable 中,并使用 .subscribe()
获得最终结果.
Calling .subscribe()
into a .subscribe()
is an anti-pattern and must be avoided at all cost. What you should do instead is merge your api calls into one single observable and get the end result with a .subscribe()
.
据我所知,以下是您应该如何转换您的可观察对象以将您的 Gizmo 数据转换为您的项目数据:
From what I see, here's how you should transform your observable to get your gizmo data into your item data:
this.myItemService.get<MyItem[]>(
new FindParameters({ name: name })
).pipe(
mergeMap((myItems: MyItem[]) => {
const gizmoRequestArray: Observable<MyItem>[] = myItems.map(item => {
return this.gizmoService.get(item.id).pipe(
map(z => {
item.gizmo = z;
return item;
})
);
});
return combineLatest(gizmoRequestArray);
})
)
.subscribe(x => this.totalCount = x.length);
这篇关于如何在需要 2 个 API 调用的 Angular/rxjs 中加载我的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!