简体   繁体   中英

how to get nested api data using nestjs httpservice (axios)

I am using nestjs HttpService.get to retrieve data from the following 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),
                       );
}

The API returns a nested array of objects among other data. I am trying to access an Array of Make_Name property without success. I have tried various observable operators none seems to work. I know I could switch to a Promise...but I want to use observables......any ideas would be much appreciated.

If Results is an array, what you need to do to create an array of the Make_Name property is to use array methods on the Results property. You have two ways to do this, given the above.

Option 1: Do everything in a single map function

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

Option 2: Use two map functions two separate getting the data and mapping it properly

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM