[英]how to get nested api data using nestjs httpservice (axios)
I am using nestjs HttpService.get to retrieve data from the following 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),
);
}
The API returns a nested array of objects among other data. API 返回一个嵌套的对象数组以及其他数据。 I am trying to access an Array of Make_Name property without success.
我试图访问 Make_Name 属性数组但没有成功。 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.
我知道我可以切换到 Promise...但我想使用 observables...任何想法将不胜感激。
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.如果
Results
是一个数组,那么创建Make_Name
属性的数组所需Make_Name
就是在Results
属性上使用数组方法。 You have two ways to do this, given the above.鉴于上述情况,您有两种方法可以做到这一点。
Option 1: Do everything in a single map
function选项 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)
);
}
Option 2: Use two map
functions two separate getting the data and mapping it properly选项 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)
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.