angular - Angular 错误:找不到类型为“object”的不同支持对象“[object Object]”。 NgFor 仅支持绑定到 Iterables,例如 Arrays

我正在我的 Angular 项目中使用 API,我得到了这个 JSON:

{
  "data": {
    "success": true,
    "historical": true,
    "date": "2022-01-01",
    "base": "MXN",
    "rates": {
      "COFFEE": 0.02158734144632395,
      "CORN": 0.008232645172711363,
      "COTTON": 0.04320921676820366,
      "SOYBEAN": 0.0036714622235960175,
      "SUGAR": 0.25680398615582695,
      "WHEAT": 0.00017592643558262669
    },
    "unit": "per bushel"
  }
}

但是当我尝试访问我的 HTML 中的数据时,我收到错误错误:找不到类型为“对象”的不同支持对象“[对象对象]”。 NgFor 仅支持绑定到 Iterables,例如我尝试使用 Object.key Object.value JSON.parse 的数组,但仍然遇到相同的错误,对此有什么帮助吗?

这是我的服务文件:

constructor(private http: HttpClient) { }

public getCommoditiesHistoricalMXN(): Observable<any>{
    return this.http.get<any>('https://www.commodities-api.com/api/' + this.enero + this.key + this.baseMXN + this.symbols)

这是我的 TS 文件:

granosHistorical: any = {};
constructor(private commoditiesS: CommoditiesService){}

ngOnInit(): void {

    this.commoditiesS.getCommoditiesHistoricalMXN().subscribe(resp => {
          this.granosHistorical = resp
          console.log(this.granosHistorical);
        });
    
    }

这是我的 HTML

<table class="table">
     <thead>
        <tr>
          <th scope="col">Mes</th>
          <th scope="col">MXN$/bu</th>
          <th scope="col">VAR</th>
        </tr>
     </thead>
     <tbody>
        <tr *ngFor="let granos of granosHistorical">
           <td>{{granos.date}}</td>
           <td>Price</td>
           <td>Var</td>
        </tr>
     </tbody>
</table>

回答1

您在响应中收到一个对象。 ngFor 指令仅适用于错误消息中所说的数组和可迭代对象。

如果您想在响应的 data 属性中包含多个项目,则响应的有效负载应如下所示:

{
    "data": [
        {
          "success": true,
          "historical": true,
          "date": "2022-01-01",
          "base": "MXN",
          "rates": {
            "COFFEE": 0.02158734144632395,
            "CORN": 0.008232645172711363,
            "COTTON": 0.04320921676820366,
            "SOYBEAN": 0.0036714622235960175,
            "SUGAR": 0.25680398615582695,
            "WHEAT": 0.00017592643558262669
        },

        {
          "success": true,
          "historical": true,
          "date": "2022-01-01",
          "base": "MXN",
          "rates": {
            "COFFEE": 0.02158734144632395,
            "CORN": 0.008232645172711363,
            "COTTON": 0.04320921676820366,
            "SOYBEAN": 0.0036714622235960175,
            "SUGAR": 0.25680398615582695,
            "WHEAT": 0.00017592643558262669
        }
      ],
      "unit": "per bushel"
    }
  }

请注意,响应的 data 属性是一个数组,因此您可以应用 ngFor 指令。

相似文章

随机推荐

最新文章