【问题标题】:Trouble retrieving data from inner observables从内部可观察对象中检索数据时遇到问题
【发布时间】:2019-03-15 14:09:44
【问题描述】:

我对这段代码有疑问。我正在尝试从与第一次获取返回的集合中的 id 相关的辅助端点收集额外的详细信息。有人可以帮助如何在返回一组可观察对象时获取实际数据。谢谢

this.http.get(`${this.apiUrl}/cinemas/location/cardiff`).pipe(
  map((data: any) => data.cinemas),
  map((cinemalist) => {
    return cinemalist.map(value => <Observable<any>>this.http.get(`https://api.cinelist.co.uk/get/cinema/${value.id}`));
  })
).subscribe(results => {
  console.log(results);
});

【问题讨论】:

标签: angular rxjs ionic4


【解决方案1】:

您可以使用switchMap 代替map,而不是forkJoin

this.http.get(`${this.apiUrl}/cinemas/location/cardiff`).pipe(
  map((data: any) => data.cinemas),
  switchMap((cinemas) => forkJoin(cinemas.map(value => <Observable<any>>this.http.get(`https://api.cinelist.co.uk/get/cinema/${value.id}`));
  }))
).subscribe(results => {
  console.log(results);
});

如果你想保持价值,你可以尝试这样的事情:

this.http.get(`${this.apiUrl}/cinemas/location/cardiff`).pipe(
  map((data: any) => data.cinemas),
  switchMap((cinemas) => forkJoin(cinemas.map(value => <Observable<any>>this.http.get(`https://api.cinelist.co.uk/get/cinema/${value.id}`))
    .pipe(map(cinema => {...cinema,value}))
  }))
).subscribe(results => {
  console.log(results);
});

【讨论】:

  • 所以事实证明我需要为每个电影院保留原始价值(价值)。除了在子查询中获取的结果之外,我如何创建一个结合原始值的结果?
  • this.http.get(https://api.cinelist.co.uk/search/cinemas/location/${town}).pipe( map((data: any) => data.cinemas), switchMap((cinemas) =​​> forkJoin(cinemas.map(value = > >this.http.get(https://api.cinelist.co.uk/get/cinema/${value.id})) ) ) ).subscribe(x => { console.log(x); });
  • 添加管道完全搞砸了?
  • 不知道,没测试过,不好意思。
【解决方案2】:
this.http.get(`https://api.cinelist.co.uk/search/cinemas/location/${town}`).pipe(
      map((data: any) => data.cinemas),
      flatMap((cinemas) =>
        forkJoin(
          cinemas.map(value => {
            return this.http.get(`https://api.cinelist.co.uk/get/cinema/${value.id}`).pipe(
              map((result: any) => {
                return { ...result, ...value };
              }));
          })
        )
      )
    ).subscribe(x => {
      console.log(x);
    });

【讨论】:

    猜你喜欢
    • 2019-01-30
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 2018-12-16
    相关资源
    最近更新 更多