Home > Enterprise >  I want to change output of API with rxjs
I want to change output of API with rxjs

Time:04-15

I have API call, where I use pipe

getCountriesListNights(){
    const r = this.http.get<any>(this.APIUrl   "/WorldMapDataNights?&year="   this.selectedYear   "&month="   this.selectedMonth  "&gender="   this.selectedGender   "&age=" this.selectedAge   "&quarter="   this.selectedQuarter).pipe(map((res) => {return res.map((res: { id: any; countryName: any; value: any; year: any; name: string; multiPolygon: any[] }) =>({countryName: res.countryName,  id: res.id,  value: res.value, year: res.year, name: res.name, multiPolygon: res.multiPolygon  }))})).subscribe(res =>{
      this.renderMapObject(res);
    });
  };

It works good, I can change the output, but I want to divide value by other API's value, when country name's are same in both API's. (I want to divide res.value by otherapi.value.)

what can I do now?

CodePudding user response:

Something like this would do the trick

getCountriesListNights(){
const r = this.http.get<any>(this.APIUrl   "/WorldMapDataNights?&year="   this.selectedYear   "&month="   this.selectedMonth  "&gender="   this.selectedGender   "&age=" this.selectedAge   "&quarter="   this.selectedQuarter).pipe(map((res) => {return res.map((res: { id: any; countryName: any; value: any; year: any; name: string; multiPolygon: any[] }) =>({countryName: res.countryName,  id: res.id,  value: res.value, year: res.year, name: res.name, multiPolygon: res.multiPolygon  }))})).subscribe(res =>{
  this.renderMapObject(res);
  this.http.get<any>(this.APIUrl   "/yourSecondApiURL).subscribe(otherapiRes =>{
     const finalResult = res.value / otherapiRes .value;
     console.log(finalResult);       
  }
});

};

it is not pretty and you could use something like

const res = await this.http.get<any>("...firstApiUrlAndMapping...").toPromise();
const res2 = await this.http.get<any>("...secondApiUrlandMapping...").toPromise();
finalResult = res.value/res2.value;
 

but both ways should work just fine.

CodePudding user response:

Okay, to achieve the aim, you need a fulfilled response from two sources. In general, the Promise.all() is giving what you need.

There are several ways to achieve your need in RxJS world. For example, the operator zipWith returns a stream that notifies of an array of results (its source and its argument inputs).

A sample you can play with:

of('Foo')
  .pipe(
    delay(1000),
    tap(() => console.log('Foo succeeded')),
    zipWith(
      of('Bar').pipe(
        delay(2000),
        tap(() => console.log('Bar succeeded'))
      ),
      of('Baz').pipe(
        delay(2500),
        tap(() => console.log('Baz succeeded'))
      )
    ),
    // You can process and transform the outcome
    map(([foo, bar, baz]) => foo   bar   baz)
  )
  .subscribe(result => {
    console.log('All succeeded:', result);
  });

https://stackblitz.com/edit/rxjs-er8zx1?file=index.ts

  • Related