如何使用nestjs httpserviceaxios获取嵌套的api数据

问题描述

我正在使用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 ...但是我想使用可观察的东西...任何想法都将不胜感激。

解决方法

如果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)
    );
}