typescript Forkjoin一个可观的数组

shstlldc  于 2023-06-07  发布在  TypeScript
关注(0)|答案(4)|浏览(120)

我有一系列可观察到的东西

const resultObservable: Observable<searchObject[]> [];
let i : 0;
keywordsArray.foreach(keyword => {
    resultObservable[i] = getSearchResult(keyword); //function returns an array of observable searchObject
    i++;
});

现在我必须把所有的resultObservable放在一起,我怎么才能做到这一点?

xlpyo6sf

xlpyo6sf1#

如果getSearchResult(keyword)返回一个对象数组,则可以使用Array.flat()将嵌套数组展平
但不是很RXJS。
这是一种Rx方式

of(keywordsArray)      // observable stream from keywords
.pipe(
  concatMap(keyword => {          // convert each keyword to search results
    return getSearchResult(keyword)
  })
)
.subscribe(searchResult => ...)

const searchResults$ = of(keywordsArray)      // observable stream from keywords
.pipe(
  concatMap(keyword => {          // convert each keyword to search results
    return getSearchResult(keyword)
  })
)
qni6mghb

qni6mghb2#

您可以使用Array.map()来迭代关键字,并使用concat()来合并它们:

const resultObservable: Observable<searchObject[]>[] = keywordsArray.map(keyword => 
    getSearchResult(keyword)
);

concat(resultObservable).subscribe(() => { /* Do Some Stuff */ })
ht4b089n

ht4b089n3#

您应该使用flatMap()或替代方案:

const resultObservable: Observable<searchObject[]> [] = keywordsArray.map(keyword => {
  return getSearchResult(keyword);
})
.reduce((x, y) => x.concat(y), []);
ctrmrzij

ctrmrzij4#

您可以使用forkJoin & of from RxJSArray.reduce来实现,如下所示:

const resultObservable = keywordsArray.map((keyword) => {
  return of(getSearchResult(keyword)); //function returns an array of searchObject
});

// forkJoin combines the the array of observables and returns Observable<searchObject[][]>
forkJoin(resultObservable)
  .pipe(
    map((res) =>
      // Array.reduce will combine the arrays and return one array that has all the objects.
      res.reduce((acc, curr) => [...acc, ...curr], [])
    )
  )
  .subscribe((res: searchObject[]) => {
    // Do here what you need with the combined result
  });

相关问题