如何在Angular 5中用ES6 Map提取API返回的车辆数据数组
解决Angular 5 HttpClient提取API返回data数组的问题
嘿,这事儿很简单,你只需要用RxJS的map操作符来提取API响应里的data数组就行,我给你两种方案,看你喜欢哪种:
方案1:在组件里直接处理响应
首先确保你已经导入了map操作符(Angular 5里要用pipeable的版本):
import { map } from 'rxjs/operators';
然后修改你的getVehicleList方法,在subscribe之前用pipe加上map操作,把响应对象转换成里面的data数组:
vehicles: Vehicle[]; getVehicleList() { this.vehicleService.getVehicleData() .pipe( // 从API返回的对象中提取data数组 map(apiResponse => apiResponse.data) ) .subscribe(data => { this.vehicles = data; console.log(JSON.stringify(data)); // 现在这里输出的就是纯车辆数组啦 }) }
方案2:把逻辑放到Service里(更推荐)
这种方式更优雅,组件不用关心API的返回结构,Service直接给组件返回需要的Vehicle[]:
先修改你的vehicleService,导入必要的模块并调整getVehicleData方法:
import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { Vehicle } from './你的接口路径'; @Injectable() export class VehicleService { constructor(private http: HttpClient) {} getVehicleData(): Observable<Vehicle[]> { // 指定API返回的类型,让TypeScript帮你做类型检查 return this.http.get<{ data: Vehicle[], _metadata: any }>('你的API接口地址') .pipe( map(response => response.data) ); } }
这样你的组件代码就可以保持原来的样子,因为Service已经帮你把data数组提取出来了,直接赋值给vehicles就行:
vehicles: Vehicle[]; getVehicleList() { this.vehicleService.getVehicleData() .subscribe(data => { this.vehicles = data; console.log(JSON.stringify(data)); }) }
为什么这么做?
RxJS的map操作符就是用来转换Observable发出的值的,这里我们把API返回的完整对象(包含data和_metadata)转换成我们需要的data数组,完美匹配你的Vehicle[]类型,还能保证类型安全。
内容的提问来源于stack exchange,提问作者venura
相关产品推荐
相关产品推荐

