首页 > 解决方案 > TypeError: data is not iterable ,在嵌套数组上使用 ngfor

问题描述

  rowData=  [{
  "label": "president",
  "contestants": [{
    "name": "john key",
    "votes": 2
  }, {
    "name": "john hi",
    "votes": 1
  }, {
    "name": "john kl",
    "votes": 1
  }]
}, {
  "label": "organizer",
  "contestants": [{
    "name": "michael skie",
    "votes": 3
  }, {
    "name": "michael e",
    "votes": 1
  }]
}, {
  "label": "secretary",
  "contestants": [{
    "name": "sampson eons",
    "votes": 2
  }, {
    "name": "sampson mji",
    "votes": 2
  }]
}]
我有一个看起来像这样的 rowData,我想使用 NGFOR 动态创建多个条形图和结果

<div *ngIf="rowData.length >0">
  <div *ngFor="let arr of rowData  let i=index">
    <div *ngFor="let elm of arr.contestants">
   <ngx-charts-bar-vertical
    [view]="view"
    [scheme]="colorScheme"
    [results]="elm"
    [gradient]="gradient"
    [xAxis]="showXAxis"
    [yAxis]="showYAxis"
    [legend]="showLegend"
    [showXAxisLabel]="showXAxisLabel"
    [showYAxisLabel]="showYAxisLabel"
    [xAxisLabel]="xAxisLabel"
    [yAxisLabel]="yAxisLabel"
    (select)="onSelect($event)">
  </ngx-charts-bar-vertical> 
  </div>
     </div>
</div>

我收到一个错误,即数据不可迭代。有人能帮我吗

标签: angularngx-charts

解决方案


我通过重新排列json解决了它

rowData = [
  [{
    "label": "president",
    "contestants": [{
      "name": "john key",
      "votes": 2
    }, {
      "name": "john hi",
      "votes": 1
    }, {
      "name": "john kl",
      "votes": 1
    }]
  }, {
    "label": "organizer",
    "contestants": [{
      "name": "michael skie",
      "votes": 3
    }, {
      "name": "michael e",
      "votes": 1
    }]
  }, {
    "label": "secretary",
    "contestants": [{
      "name": "sampson eons",
      "votes": 2
    }, {
      "name": "sampson mji",
      "votes": 2
    }]
  }]
]

<div *ngIf="rowData.length >0">
  <div *ngFor="let arr of rowData  let i=index">
    <div *ngFor="let elm of arr.contestants">
   <ngx-charts-bar-vertical
    [view]="view"
    [scheme]="colorScheme"
    [results]="elm"
    [gradient]="gradient"
    [xAxis]="showXAxis"
    [yAxis]="showYAxis"
    [legend]="showLegend"
    [showXAxisLabel]="showXAxisLabel"
    [showYAxisLabel]="showYAxisLabel"
    [xAxisLabel]="xAxisLabel"
    [yAxisLabel]="yAxisLabel"
    (select)="onSelect($event)">
  </ngx-charts-bar-vertical> 
  </div>
     </div>
</div>

我移动了结果 rowData[0]; 它解决了我的问题


推荐阅读