我如何返回作为同一可观察对象加入的两个可观察对象

时间:2020-01-17 20:49:19

标签: typescript rxjs

我很难让函数返回。它有一个条件,该条件将返回一个Observable,另一个条件是,我想返回两个Observable的结果,并将它们成功合并在一起。

类似这样的东西。

getSearchFeed(): Observable<items[]> {
   if (this.condition) {
     return this.populateItemsArray();            //function Returns Items Array Observable
   } 

   //second condition
   const someItems = this.populateSearch();       //function Returns Items Array Observable
   const otherItems = this.populateOtherSearch(); //function Returns Items Array Observable

   return forkJoin(someItems,otherItems)
    .pipe((res:Array) => {
      return [...res[0],...res[1]];
   });
}

其他帖子谈到了加入结果,我了解如何订阅和加入。我的问题更多是关于如何为第二个条件返回一个Observerable。

我尝试过的其他一些事情

return forkJoin(someItems,otherItems)
 .pipe(map((res:Array<Observerable<Items[]>>) => {
    return [...res[0],res[1]];
});

const source = of([someItems,otherItems]);
const merged = source.pipe(mergeMap( q => forkJoin(...q)));
return merged;

1 个答案:

答案 0 :(得分:1)

在这种情况下,可以使用toArray() RxJS运算符。根据{{​​3}},toArray()运算符

收集所有放射源,并在放射源完成后以阵列的形式发出。

这是您的代码的外观。这样做会将返回的可观察值连接到一个数组中。

import { forkJoin } from 'rxjs';
import { toArray } from 'rxjs/operators';

getSearchFeed(): Observable<items[]> {
   if (this.condition) {
     return this.populateItemsArray();            //function Returns Items Array Observable
   } 

   //second condition
   const someItems = this.populateSearch();       //function Returns Items Array Observable
   const otherItems = this.populateOtherSearch(); //function Returns Items Array Observable

   return forkJoin(someItems,otherItems)
     .pipe(
       toArray(),
     );
}

编辑:我只是注意到返回类型,所以我应该将返回的可观察对象展平为单个数组。在这种情况下,您可以简单地在map运算符中使用documentation,并且应该将其展平为单个数组。

import { forkJoin } from 'rxjs';
import { map } from 'rxjs/operators';

getSearchFeed(): Observable<items[]> {
   if (this.condition) {
     return this.populateItemsArray();            //function Returns Items Array Observable
   } 

   //second condition
   const someItems = this.populateSearch();       //function Returns Items Array Observable
   const otherItems = this.populateOtherSearch(); //function Returns Items Array Observable

   return forkJoin(someItems,otherItems)
     .pipe(
       map(res => res.flat(2))
     );
}