简体   繁体   English

在Angular中将多个Http流与RxJS Observables结合

[英]Combining multiple Http streams with RxJS Observables in Angular

I tried to make the following stream work, with map and flatMap, however it does what it should do, but the code is not optimal eg the second time I am using flatMap, I never read it's response value, but I just don't know how to continue the flow without, and if I remove it I get an error 我试图使以下流与map和flatMap一起工作,但是它做了它应该做的事情,但是代码不是最佳的,例如,我第二次使用flatMap时,我从未读取过它的响应值,但是我只是不这样做不知道如何继续执行流程,如果删除流程,则会出现错误

Argument of type 'Observable' is not assignable to parameter of type '(outerValue: any, innerValue: void, outerIndex: number, innerIndex: number) => any' 类型'Observable'的参数不能分配给类型'(outerValue:any,innerValue:void,externalIndex:number,innerIndex:number)=> any'的参数

So how can I make this better ? 那么我该如何做得更好呢?

  person;
  facility;
  apiUrl1: string = 'http://localhost:3000/person/?';
  apiUrl2: string = 'http://localhost:3000/facility/?';
  apiUrl3: string = 'http://localhost:3000/exposure/?';

  constructor(private http: HttpClient) { }

  getData(arg): Observable<any> {
    return this.http.get(this.apiUrl1 + arg.data)
      .map((response: any) =>
        this.person = response
      )
      .flatMap((response: any) => this.http.get(this.apiUrl2 + response.val1)
        .map((response: any) => {
          this.facility = response
        })
        .flatMap((response: any) => this.http.get(this.apiUrl3 + this.person.val2)
          .map((response: any) => response.val5 * this.facility.val3)))
  }
}

If your intention of having variables this.person , this.facility and this.exposure is to "retain" the values just so that you can re-use the results of your previous http call, then there is no need to do so. 如果您打算使用变量this.personthis.facilitythis.exposure只是为了“保留”这些值,以便您可以重用先前的http调用的结果,则无需这样做。 With the help of .forkJoin and array destructuring , you can eliminate them. 借助.forkJoin数组解构 ,您可以消除它们。

Here is a much shorter, succinct and readable code: 这是一个更简短,简洁易读的代码:

getData(arg): Observable<any> {
    return this.http.get(this.apiUrl1 + arg.data)
        .flatMap((person: any) => Observable.forkJoin([...this.http.get(this.apiUrl2 + person.val1), this.http.get(this.apiUrl3 + person.val2)]))
        .map(([facility, exposure]) => exposure.val5 * facility.val3)
}

P/S: give proper names to your variables (as opposed to just naming them as response ) helps a tonne P / S:给变量取适当的名称(而不是仅仅将它们命名为response )有助于吨

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

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