如何使用@nestjs/axios 发出 api Get 请求

How to make an api Get request using @nestjs/axios

我想从 OpenWeatherMap 获取一个城市的天气信息,但我得到一个奇怪的 JSON 响应

回复我得到的

{ “名称”:“达拉斯”, “天气”: { “资源”: { “资源”: {} } }, “_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;
  }
}

@nestjs/axios 将所有 HTTP 调用包装在 RxJS Observables 中,这有点像增压回调。打开可观察流后,您要么只需要在该流内工作(使用 .pipe 和开始映射数据时的运算符),要么需要将可观察到的对象转换为承诺。最简单的方法是使用 lastValueFrom 并用它包裹整个 Observbale (lastValueFrom(this.http.get().pipe()))。如果你选择前者,tapswitchMap 也可能是两个操作符,否则 lastValueFrom 方法可以被 await 正常编辑承诺。