I looked at similar questions, but none of them helped me. I am going to receive an object like the following:
{
"batch": "1"
"batchsize": "212"
"bmrnumber": "23232"
"fieldname": "Batch"
"id": 5122315436163072
"pelletsize": "1"
"project": "test"
}
My http service to receive it:
this.http.get('/api/getbatch/' + this.authService.namespace + '/' + ID, options)
.map(res => res.json());
and finally, in the i called the service in this way:
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 Component to receive show as table format:
<table id="Batch">
<tr *ngFor="let batchvalues of getbatches ;let i = index;">
<td><tr>
<th>Product Name</th>
<td> {{batchvalues.product}}</td>
</tr>
</table>
Unfortunately, when the page loads it complains with:
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
So, what is going wrong with this code?
As a response you getting is an Object not Array of Objects (as per your console.log details):
There are two ways:
If you are receiving Single Object every time then no need to use *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>
Another one if that needs to be an array then ask the person who gave you an API to change its type from Object to Array of Objects and then you can use:
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>