出现错误,找不到类型为'object'的其他支持对象'[object Object]'。 NgFor仅支持绑定到Iterables,例如数组

问题描述 投票:0回答:2

我看着类似的问题,但是没有一个对我有帮助。我将收到如下对象:

{
    "batch": "1"
    "batchsize": "212"
    "bmrnumber": "23232"
    "fieldname": "Batch"
    "id": 5122315436163072
    "pelletsize": "1"
    "project": "test"
}

我的http服务接收它:

this.http.get('/api/getbatch/' + this.authService.namespace + '/' + ID, options)
  .map(res => res.json());

最后,在i中,我以这种方式调用了服务:

    getbatches: any = [];
constructor(private batchServce:BatchService){}
ngOnInit(){
        this.  this.testbatch();

    }
testbatch() {
  this.batchServce.getbatch(this.batchID).subscribe(res => {
    this.getbatches = res.json();
    console.log('-====>' + JSON.stringify(this.getbatches));
  });
 }

HTML组件以表格格式接收显示:

<table id="Batch">
 <tr *ngFor="let batchvalues of getbatches ;let i = index;"> 
 <td><tr>
   <th>Product Name</th>
   <td> {{batchvalues.product}}</td>
   </tr>                           
</table>

不幸的是,页面加载时抱怨:

找不到类型为'object'的其他支持对象'[object Object]'。 NgFor仅支持绑定到Iterables,例如数组。

那么,这段代码出了什么问题?

angular angular-template
2个回答
1
投票
作为响应,您得到的是对象而不是对象数组

(根据您的console.log详细信息):

有两种方法:

如果您每次都接收单个对象,则无需使用* ngFor:

testbatch() { this.batchServce.getbatch(this.batchID).subscribe(res => { this.getbatches = res; console.log('-====>' + JSON.stringify(this.getbatches)); }); }

HTML:

<your table html> <td>{{getbatches.project}}</td> <td>{{getbatches.batch}}</td> etc. </your table markup>

如果需要将数组作为另一个数组,请让给您API的人将其类型从Object更改为Object Array,然后您可以使用:

testbatch() { this.batchServce.getbatch(this.batchID).subscribe(res => { this.getbatches = res; console.log('-====>' + JSON.stringify(this.getbatches)); }); }

HTML:

<table id="Batch"> <tr *ngFor="let batchvalues of getbatches;let i = index;"> <th>Product Name</th> <td> {{batchvalues.product}} </td> </tr> </table>


0
投票
这里不需要.json()方法

testbatch() { this.batchServce.getbatch(this.batchID).subscribe(res => { this.getbatches = res; console.log('-====>' + JSON.stringify(this.getbatches)); }); }

© www.soinside.com 2019 - 2024. All rights reserved.