【发布时间】:2021-12-31 21:04:59
【问题描述】:
有两个模型如下所示:
export class Game {
id: number;
name: string;
platform: number;
}
export class Platform {
id: number;
name: string;
}
拥有一个可观察的 Game 对象数组,该数组具有与 Platform 对象相关的 platformId 属性。为了更好地理解,我创建了两种单独的方法来获取我的游戏列表和另一种方法来获取基于 id 的平台。
getGames(): Observable<Game[]> {
return of([
{
id: 1,
name: 'god of war',
platform: 1,
},
{
id: 2,
name: 'halo',
platform: 2,
},
]);
}
getPlatform(id): Observable<Platform> {
if (id === 1)
return of({
id: 1,
name: 'ps4',
});
if (id === 2)
return of({
id: 2,
name: 'xbox',
});
}
现在我在 rxjs 的两个运算符 (switchMap,forkJoin) 的帮助下达到了这一点:
this.getGames()
.pipe(
switchMap((games: Game[]) =>
forkJoin(
games.map((game) =>
forkJoin([this.getPlatform(game.platform)]).pipe(
map(([platform]) => ({
game: game.name,
platform: platform.name,
}))
)
)
)
)
)
.subscribe((v) => {
console.log(v);
this.gamesV2 = v;
});
和我的最终结果:
[
{
game: "god of war"
platform: "ps4"
},
{
game: "halo"
platform: "xbox"
}
]
是否有可能以更简单的方式实现这一目标? StackBlitz
【问题讨论】:
标签: rxjs observable fork-join switchmap