【问题标题】:Switching array of Observables into Observable of their results将 Observables 数组转换为 Observable 的结果
【发布时间】:2020-08-12 15:50:44
【问题描述】:

以下代码正在运行。其目的是将返回匹配项的搜索结果转换为每个匹配项的详细信息。

可能有更好的写法:

    fromEvent(this.searchInput.nativeElement, 'input').pipe(
      debounceTime(500),
    ).subscribe(async _ => {
      const results = await this.database.search(this.searchText);
      const arrayOfobservables = combineLatest(results.map(result => this.database.getDetails(result.objectID)));
      this.searchResults$.next(arrayOfobservables)
    });

    this.details$ = this.searchResults$.pipe(
      switchMap(val => val)
    )

我正在努力的部分是将 observables 数组转换为我可以在 UI 中呈现的 observable 数组。

尤其是switchMap(val => val) 对我来说看起来很奇怪。关于如何真正使这段代码更干净的任何想法?

【问题讨论】:

标签: angular typescript rxjs


【解决方案1】:

您应该可以switchMap 兑现承诺:https://stackoverflow.com/questions/44784660/how-does-switchmap-resolve-a-promise#:~:text=As%20you%20can%20see%2C%20getHero,()%20receives%20a%20Promise%20back

试试:

this.details$ = fromEvent(this.searchInput.nativeElement, 'input').pipe(
      debounceTime(500),
      switchMap(_ => this.database.search(this.searchText)),
      switchMap(results => combineLatest(results.map(result => this.database.getDetails(result.objectID)))),
      tap(_ => { console.log(_) }), // see what you get here, it should hopefully be an array
    );

【讨论】:

    猜你喜欢
    • 2020-12-16
    • 2021-12-04
    • 1970-01-01
    • 2023-03-16
    • 2017-07-30
    • 2018-06-06
    • 2016-06-02
    • 2014-10-24
    • 2020-12-01
    相关资源
    最近更新 更多