获取错误找不到类型 'object' 的不同支持对象“[object Object]”。 NgFor 仅支持绑定到 Iterables,例如 Arrays

Getting Error Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

我看过类似的问题,但其中 none 对我有帮助。我将收到如下对象:

{
    "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());

最后,在我以这种方式调用服务时:

    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 格式:

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

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

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

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

这里不需要 .json() 方法

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

您得到的响应是对象而不是对象数组(根据您的 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>