将可观察变量数组转换为其结果可观察变量

时间:2020-08-12 15:50:44

标签: angular typescript rxjs

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

可能有一种更好的方式编写此代码:

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

我正在努力的部分是将可观察对象数组转换为可以在UI中显示的可观察数组。

特别是switchMap(val => val)对我来说看起来很奇怪。关于如何使此代码更清洁的任何想法?

1 个答案:

答案 0 :(得分: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
    );