【问题标题】:exact array using ES 6 from an array of object从对象数组中使用 ES 6 的精确数组
【发布时间】:2018-03-25 14:51:55
【问题描述】:

我正在使用 Angular 5 http 客户端从 API 获取数据。这是我的订阅部分

vehicles: Vehicle[];
getVehicleList() {
this.vehicleService.getVehicleData()  
.subscribe(data => { 
    this.vehicles = data
    console.log(JSON.stringify(data));} 
)
}

车辆界面

  export interface Vehicle {
    type: string;
 } 

我得到一个像这样的 JSON

       {
  "data": [
    {
      "type": "bus"
    },
    {
      "type": "truck"
    },
    {
      "type": "car"
    }
  ],
  "_metadata": null
}

我只想使用 map 函数从上面获取数组。有人可以帮我解决这个问题吗?

【问题讨论】:

  • data.data 呢?
  • @KhauriMcClain - 我也试过了。在 IDE 中出现错误,因为 [ts] 属性 'data' 在类型 'Vehicle[]' 上不存在
  • 然后改变你的界面?
  • 您确定this.vehicles = data.data 不起作用吗?还是你不小心做了this.vehicles.data = ...
  • 不,我试过你写的。由于类型“车辆[]”上不存在属性“数据”而出现错误-

标签: javascript angular ecmascript-6


【解决方案1】:

我不确定您在这里问什么,但正如 Khauri 指出的那样,您可以使用 data.data 获取数据数组。 如果你想在它上面使用地图,它看起来像这样:

data.data.map(element => console.log(element.type))

这会打印出来

巴士 卡车 汽车

[编辑] 如果你只想获取数组,你应该使用data.data 假设您使用的是 typescript,您需要在 Vehicule 接口中添加一个 data 字段,这是一个数组。

【讨论】:

  • 为什么使用 map 而不是 forEach?
  • 这也不会返回它只会记录的东西
  • @Alexandre Rozier- 我将数组定义为数据:Array;或 data: string[] 像这样。但仍然收到错误 [ts] Property 'data' does not exist on type 'Vehicle[]'
【解决方案2】:

在我看来,之前的 cmets 解决方案应该可行。

请确保您已将代码更改为以下内容:

    vehicles: Vehicle[];
    getVehicleList() {
        this.vehicleService.getVehicleData()
        .subscribe(data => { 
             this.vehicles = data.data;
        })
    }

【讨论】:

  • 已经给出了答案。请参阅我对此的回复
  • 你能添加几行你的verhicleService.getVehicleData()函数吗?
猜你喜欢
  • 2012-09-22
  • 1970-01-01
  • 2021-10-19
  • 2015-08-05
  • 2018-11-02
  • 2021-04-29
  • 2019-09-07
  • 1970-01-01
  • 2021-12-17
相关资源
最近更新 更多