【问题标题】:how to get nested api data using nestjs httpservice (axios)如何使用nestjs httpservice(axios)获取嵌套的api数据
【发布时间】:2020-12-19 01:41:01
【问题描述】:

我正在使用 nestjs HttpService.get 从以下 API 检索数据:

 getVehicleMake(): Observable<AxiosResponse<any>> {
   return  this.httpService.get('https://vpic.nhtsa.dot.gov/api/vehicles/getallmakes?format=json')
                 .pipe(
                       map(response => response.data.Results),
                       map(obj => obj.Make_Name),
                       );
}

API 在其他数据中返回一个嵌套的对象数组。我试图访问 Make_Name 属性的数组但没有成功。我尝试了各种可观察的运算符,但似乎都不起作用。我知道我可以切换到 Promise...但我想使用 observables...任何想法都将不胜感激。

【问题讨论】:

    标签: javascript node.js axios nestjs rxjs-observables


    【解决方案1】:

    如果Results 是一个数组,创建Make_Name 属性的数组需要做的是在Results 属性上使用数组方法。鉴于上述情况,您有两种方法可以做到这一点。

    选项 1:在单个 map 函数中完成所有操作

    getVehicleMake(): Observable<AxiosResponse<any>> {
      return  this.httpService.get('https://vpic.nhtsa.dot.gov/api/vehicles/getallmakes?format=json')
        .pipe(
          map(response => response.data.Results.map(result => result.Make_Name)
        );
    }
    

    选项 2:使用两个 map 函数,两个分开获取数据并正确映射

    getVehicleMake(): Observable<AxiosResponse<any>> {
      return  this.httpService.get('https://vpic.nhtsa.dot.gov/api/vehicles/getallmakes?format=json')
        .pipe(
          map(response => response.data.Results),
          map((results) => results.map(result => result.Make_Name)
        );
    }
    

    【讨论】:

    • 谢谢.....我遇到了第二个地图操作员的问题。我注意到你在第一张地图和第二张地图之间省略了逗号……小错误
    猜你喜欢
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 2022-09-23
    • 2020-08-10
    • 1970-01-01
    • 2020-09-10
    • 2018-07-05
    相关资源
    最近更新 更多