HTTP Obserables数组到Async-Pipeable Observable

问题描述 投票:0回答:3

我正在尝试根据初始请求的结果进行一系列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管道解包的内容?

StackBlitz

javascript angular rxjs observable rxjs6
3个回答
0
投票

如果要在观察台上使用异步等待,则必须从中作出承诺。您可以在可观察对象上使用toPromise()方法。此可观察值将转换为Promise,因此您可以在其上使用await


0
投票

您想要一些喜欢的东西吗?

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])))
  }))

0
投票

想要将您的观测值zip,然后flatMap的声音。结果将是一个Observable,其中T是单个Observable的返回类型。

喜欢这个:

this.residentData$ = this.planet$.pipe(
  flatMap(planets => zip(...planets.residents.map(planet =>
      this.starWarsService.getEntityById("people", planet.split("/")[5])))
  ),
  tap(result => {
    console.log('result', result);
  }),
);
© www.soinside.com 2019 - 2024. All rights reserved.