代码之家  ›  专栏  ›  技术社区  ›  Rolando

在angular2/4RXJS中,处理从多个http观察返回的数据串联的正确方法是什么?

  •  1
  • Rolando  · 技术社区  · 8 年前

    this.myHttpService.graburl1data()
        .subscribe(
            response => {
                if(!this.mylist) {
                    this.mylist = []
                    this.mylist = this.mylist.concat(response);
                } else {
                    this.mylist = this.mylist.concat(response);
                }
    
                this.myHttpService.graburl2data()
                    .subscribe(
                        response => {
                            if(!this.mylist) {
                                this.mylist = []
                                this.mylist = this.mylist.concat(response);
                            } else {
                                this.mylist = this.mylist.concat(response);
                            }
                        });
            });
    

    2 回复  |  直到 8 年前
        1
  •  3
  •   cartant    8 年前

    您的代码片段似乎表明请求之间没有依赖关系,因此您可以使用 forkJoin 平行排列:

    import { Observable } from "rxjs/Observable";
    import "rxjs/add/observable/forkJoin";
    
    Observable.forkJoin(
      this.myHttpService.graburl1data(),
      this.myHttpService.graburl2data()
    )
    .subscribe(
      (responses) => {
        // ... responses[0] is the response from this.myHttpService.graburl1data
        // ... etc.
      }
    );
    

    responses 将是一个响应数组,按照请求可观察对象传递到的顺序排列 分叉连接 .

    如果您希望连续执行请求,请使用 concat toArray

    import { Observable } from "rxjs/Observable";
    import "rxjs/add/observable/concat";
    import "rxjs/add/operator/toArray";
    
    Observable.concat(
      this.myHttpService.graburl1data(),
      this.myHttpService.graburl2data()
    )
    .toArray()
    .subscribe(
      (responses) => {
        // ... responses[0] is the response from this.myHttpService.graburl1data
        // ... etc.
      }
    );
    
        2
  •  1
  •   Max Koretskyi    4 年前

    假设您有两个请求,每个请求返回一个发出 数组

    const response1 = of([1, 2, 3]);
    const response2 = of([4, 5, 6]);
    

    您希望将这些值作为一个值流-展平。您可以使用运算符的组合来实现这一点:

    const merged = merge(response1, response2).mergeMap((a) => {
      return a;
    });
    
    merged.subscribe((v) => {
      console.log(v);
    });
    

    1
    2
    3
    4
    5
    6
    

    你可以阅读更多关于 merge here .

    在您的情况下,您将获得 response http :

    const response1 = this.myHttpService.graburl1data(),
    const response2 = this.myHttpService.graburl2data()
    ...
    

    import { merge } from 'rxjs/observable/merge';
    import 'rxjs/add/operator/mergeMap';
    
    const merged = merge(
      this.myHttpService.graburl1data(),
      this.myHttpService.graburl2data()
    ).mergeMap((a) => {
      return a;
    });
    
    merged.subscribe((v) => {
      console.log(v);
    });
    
    推荐文章