Я пытаюсь использовать контент, который первый запрос API по другому запросу API, но безуспешно. Мне нужно сделать второй запрос только после того, как первый будет выполнен.
Прямо сейчас это то, что я получил до сих пор:
@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)),
),
);
}
}
Вы можете использовать код состояния, чтобы определить, был ли запрос успешным, или даже не определить, есть ли у него данные, если это необходимо.
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)),),
}
}
),
Я думаю, вы можете использовать оператор switchMap для достижения ожидаемого результата. Вы можете внести небольшие изменения, чтобы он соответствовал вашим потребностям.
@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)),
}
}