Code Worm
Code Worm

Reputation: 333

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 e.g 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

Argument of type 'Observable' is not assignable to parameter of type '(outerValue: any, innerValue: void, outerIndex: 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)))
  }
}

Upvotes: 0

Views: 479

Answers (1)

CozyAzure
CozyAzure

Reputation: 8478

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. With the help of .forkJoin and array destructuring, you can eliminate them.

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

Upvotes: 1

Related Questions