【问题标题】:Initialize observable with the result of other observable用其他 observable 的结果初始化 observable
【发布时间】:2019-12-18 22:22:10
【问题描述】:

我有 2 个请求。

  1. getCurrentBook(): Observable<Book>
  2. getDetailedInfo(bookId): Observable <BookDetailed>

它们都返回带有信息的可观察对象,但是要使用第二个请求,我必须确保我收到了来自第一个请求的信息,因为 bookId 在响应中。

我知道我可以在其他订阅中订阅,但是这个解决方案似乎对我没有吸引力。一定有更优雅的方式。

现有的解决方案

getCurrentBook().subscribe(res => {
  getDetailedInfo(res.id).subscribe(...);
})

我知道它应该看起来像:

booksSubs = getCurrentBook().pipe(
  map(res => 
    {this.currentBook = res}
   )
  )
detailedSubs = getDetailedInfo(this.currentBook.id).pipe(
  map(res => 
    {this.detailed = res}
   )
  )

this.subscriptions.push(SOME OPERATOR(booksSubs, detailedSubs).subscribe();

但更高的选项不起作用,因为我需要第一个可观察的结果来初始化第二个。

【问题讨论】:

    标签: rxjs observable


    【解决方案1】:

    您可以使用一些“扁平化”运算符来实现它,例如mergeMap

    const currentBookDetails$ = getCurrentBook().pipe(
      mergeMap(book => getDetailedInfo(book.id))
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      相关资源
      最近更新 更多