我想從 OpenWeatherMap 獲取一個城市的天氣資訊,但我得到了一個奇怪的 JSON 回應

我得到的回應
{ "name": "dallas", "weather": { "source": { "source": {} } }, "_id": "61c335daeb8c6b030489996b", "__v": 0 }
cities.service.ts
@Injectable()
export class CitiesService {
constructor(
@InjectModel('City') private readonly cityModel: Model<City>,
private readonly httpService: HttpService
) {}
async createCity(createCityDto: CreateCityDto) {
const { name } = createCityDto;
// Get city weather from OpenWeatherMap
const weather = await this.httpService
.get(
`api.openweathermap.org/data/2.5/weather?q=${name}&appid=${process.env.OPEN_WEATHER_API_KEY}`,
)
.pipe(
map((response) => response.data),
map((data) => data),
);
console.log(weather);
const city = new this.cityModel({
name,
weather,
});
await city.save();
return city;
}
}
uj5u.com熱心網友回復:
@nestjs/axios將所有 HTTP 呼叫包裝在RxJS Observables 中,這有點像增壓回呼。一旦您打開一個可觀察流,您要么只需要在該流中作業(在.pipe您開始映射資料時使用and 運算子),要么您需要將 Observable 轉換為承諾。最簡單的方法是使用lastValueFrom并用它 ( lastValueFrom(this.http.get().pipe()))包裹整個 Observbale 。如果你去同前,tap并switchMap可能會是兩家運營商獲得的以及掛起,否則lastValueFrom方法可以await編為一個正常的承諾。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/390093.html
