我正在尝试根据初始请求的结果进行一系列XHR GET。我有一个要观察的辅助请求的可观察对象数组,可以使用Array.map对其进行迭代并按顺序订阅以记录其所有返回值,但是我不明白如何将它们格式化为平坦的可观察对象我可以使用async
管道的单一订阅打印到屏幕上:
ngOnInit() {
// initial request - returns data on a planet
this.planet$ = this.starWarsService.getEntityById("planets", "1");
this.residentData$ = this.planet$.pipe(
map(planets =>
planets.residents.map(planet =>
// get character data for each resident, `split` just grabs the index to construct the URL
this.starWarsService.getEntityById("people", planet.split("/")[5])
)
),
tap(results => {
results.map(result => {
result.subscribe(data => {
// this prints resident/character data correctly
console.log("data", data);
});
});
})
);
}
async
管道解包的内容?如果要在观察台上使用异步等待,则必须从中作出承诺。您可以在可观察对象上使用toPromise()方法。此可观察值将转换为Promise,因此您可以在其上使用await
您想要一些喜欢的东西吗?
this.planet$=this.starWarsService.getEntityById("planets", "1").pipe(
share()) //<--pipe(share()) is for only one call
this.residentData$ = this.planet$.pipe(
switchMap((planet:any)=>{
//with each resident create an observable and use forkJoin
return forkJoin(planet.residents.map(x=>
this.starWarsService.getEntityById("people",x.split("/")[5])))
}))