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)),
),
);
}
}
CodePudding user response:
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)),
}
}
CodePudding user response:
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)),),
}
}
),