出现错误找不到类型为“对象”的其他支持对象“ [对象对象]”。 NgFor仅支持绑定到可迭代对象,例如数组

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

{
    "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>

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

  

找不到类型为“对象”的其他支持对象“ [对象对象]”。 NgFor仅支持绑定到数组等Iterable。

那么,这段代码怎么了?

wazwsx 回答:出现错误找不到类型为“对象”的其他支持对象“ [对象对象]”。 NgFor仅支持绑定到可迭代对象,例如数组

作为响应,您得到的是对象而不是对象数组(根据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的人将其类型从“对象”更改为“对象数组”,然后您可以使用:

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>
,

这里不需要.json()方法

 testbatch() {
  this.batchServce.getbatch(this.batchID).subscribe(res => {
    this.getbatches = res;
    console.log('-====>' + JSON.stringify(this.getbatches));
  });
 }
本文链接:https://www.f2er.com/3167987.html

大家都在问