合并来自多个rxjs observables

时间:2018-03-07 13:51:22

标签: javascript angular rxjs reactive-programming rxjs5

我有一个自动完成输入,当用户输入时,从多个端点获取数据,例如:

//service call to fetch data and return as single observable
getAutocompleteSuggestions() {
    const subs$ = [
        this.http.get(endpoint1),
        this.http.get(endpoint2),
        this.http.get(endpoint3)
    ];

    return Observable.forkJoin(...subs$);
}

每个端点都返回以下格式的数据:

{ data: [], status: xyz }

我想使用switchmap,因为我只想显示最终调用的结果,并尝试了以下内容:

   this.getAutocompleteSuggestions(query)
          .switchMap(res => {
             return res.data;
           })
          .subscribe((results: any) => {
            this.results = results;
          });

但是' res'在switchmap中是一个数组,任何想法结果如何包含一个包含任意数量的observable响应数据的单个数组?

2 个答案:

答案 0 :(得分:3)

我不完全明白你想要什么,但我认为就是这样:

$filter: Subject<string> = new Subject(); //I guess we have some value to filter by??

将值推送到主题:

this.$filter.next(myNewValue);

在构造函数或init中:

this.$filter
   .switchMap(filterValue => { //Get the values when filter changes
       subs$ = [
         this.http.get(endpoint1 + filterValue),
         this.http.get(endpoint2 + filterValue),
         this.http.get(endpoint3 + filterValue)
       ];

       return Observable.forkJoin(...subs$);
   })
   .map(results => { //now map you array which contains the results
      let finalResult = [];
      results.forEach(result => {
          finalResult = finalResult.concat(result.data)
      })
      return final;
   })
   .subscribe(); //Do with it what you want

当我们为我们的主题添加新值时,将再次执行整个蒸汽。如果有任何请求,SwitchMap将取消所有就绪请求。

答案 1 :(得分:0)

我使用了类似的东西,到目前为止运作良好:

        let endpoint1 = this.http.get(endpoint1);
        let endpoint2 = this.http.get(endpoint2);
        let endpoint3 = this.http.get(endpoint3);

        forkJoin([endpoint1, endpoint2, endpoint3])
          .subscribe(
            results => {
              const endpoint1Result = results[0].map(data => data);
              const endpoint2Result = results[1].map(data => data);
              const endpoint3Result = results[2].map(data => data);

              this.results = [...endpoint1Result, ...endpoint2Result, ...endpoint3Result];
            },
            error => {
              console.error(error);
            }
          );

显然这是一个非常简单的例子,您将能够更好地处理结果以满足您的需求。