'NestJS use the content of a API call on another API call and return the content of the last API call

I'm trying to use the content that the first API request on another API request but didn't had any success. I need to do the second request only after the first is done.

Right now this is what I got so far:

@Injectable()
export class WeatherService {
  constructor(private httpService: HttpService) {}
  getWeather(city: GetWeatherDto): Observable<AxiosResponse<any>> {
    return this.httpService.post(`http://localhost:3000/cities`, city).pipe(
      map((response) => response.data),
      tap((data) =>
        this.httpService
          .get(
            `https://api.openweathermap.org/data/2.5/weather?id=${data.city_id}&appid=APIKEY&lang=pt_br`,
          )
          .pipe(map((response) => response.data)),
      ),
    );
  }
}


Solution 1:[1]

I think you can use the switchMap operator to achieve the expected result. You might make some small changes to make it fit your needs.

@Injectable()
export class WeatherService {
  constructor(private httpService: HttpService) {}
  getWeather(city: GetWeatherDto): Observable<AxiosResponse<any>> {
    return this.httpService.post(`http://localhost:3000/cities`, city).pipe(
      switchMap((response) =>
      this.getCityWheaterById(response.data.city_id)),
      
    );
  }

 private getCityWheatherById(id: string) {
   this.httpService
          .get(
            `https://api.openweathermap.org/data/2.5/weather?
             id=${id}&appid=APIKEY&lang=pt_br`,
          ).pipe(map((response) => response.data)),
  }
}



Solution 2:[2]

You can use the status code to determine if the request was successful or not even determine if it has data if needed.

tap((response) =>
 if (response.status == 200){
   if (response.data){
     this.httpService.get(`https://api.openweathermap.org/data/2.5/weather?id=${data.city_id}&appid=APIKEY&lang=pt_br`,).pipe(map((response) => response.data)),),
    }
 }
),

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mustapha Afkir
Solution 2 dreamer's redemption