Search code examples
angularobservable

Complete 1st api call , edit its response and then make another call using the response


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 using the response of the first API?


Solution

  • 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]);