繁体   English   中英

结合来自多个rxjs可观察量的结果

[英]combining results from multiple rxjs observables

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

//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;
          });

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

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

$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将取消所有就绪请求。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM