Home > database >  Complete 1st api call , edit its respone and then make another call
Complete 1st api call , edit its respone and then make another call

Time:06-24

I am using callbacks for combining two observables :

this._containerService.portlist(this.locationDetails.LocationType)
        .subscribe(res=>{
          this.portId = res.filter(port=>port.portCode ==result.locationAddress.portCode)[0].id;
          this._portAddressService.getPortAddress(this.portId,this.locationDetails.LocationType).subscribe(res=>
            {
              this.portDetails = res.records[0];

}}

It is not an efficient method. Is there any way I can make use of an operator to complete the first observable , modify its response and then call another api.

CodePudding user response:

You can use the 'switchMap' operator.

this._containerService.portlist(this.locationDetails.LocationType)
    .pipe(
       switchMap(res => {
         this.portId = res.filter(port=>port.portCode ==result.locationAddress.portCode)[0].id;
         return this._portAddressService.getPortAddress(this.portId,this.locationDetails.LocationType
       }))
        .subscribe(res => this.portDetails = res.records[0]);

CodePudding user response:

Adding on Riorudo's answer, you can go further


this._containerService
  .portlist(this.locationDetails.LocationType)
  .pipe(
    map(res => res.find(({ portCode }) => portCode === result.locationAddress.portCode),
    pluck('id'),
    switchMap(id => this._portAddressService.getPortAddress(id, this.locationDetails.LocationType),
    map(({ records }) => records[0]),
    tap(record => this.portDetails = record)
  ).subscribe(() => {
    console.log('Port details set');
  });

Very declarative, eases the reading so much

  • Related