本文介绍了尝试在Angular中差异'[object Object]'时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
看起来像HTML中的运费变量有问题:
Looks like something wrong with freight variable in HTML:
下面是代码
freight.service.ts
=======================
getFreight (): Promise<Freight[]> {
return this.http.get(this.freightUrl)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || { };
}
freightList.component.ts
========================
getFreight() {
this.freightService
.getFreight()
.then(freight => this.freight = freight)
.catch(error => this.error = error); // TODO: Display error message
}
freightList.component.html
============================
<tr *ngFor="let frght of freight">
<td>{{frght.grp}} - {{frght.grpname}}</td>
<td>{{frght.subgrp}} - {{frght.subgrpname}}</td>
<td>{{frght.prodno}} - {{frght.prodname}}</td>
<td>{{frght.percent}}</td>
<td>{{frght.effective_date}}</td>
<td><button (click)="deleteFreight(frght, $event)" class="btn btn-danger btn-sm"><span class="glyphicon glyphicon-remove"></span> Remove</button></td>
<td><button (click)="editFreight(frght)" class="btn btn-warning btn-sm"><span class="glyphicon glyphicon-edit"></span> Edit</button></td>
</tr>
Response body
==================
[{
"effective_date": "01/01/2016",
"grp": "01",
"grpname": "STOPS/FLEX HOSES/COVER PLATES",
"id": "1",
"percent": "10",
"prodname": "DWV PVC PIPE 100MM X 6MTR SN6 SWJ",
"prodno": "1400200",
"subgrp": "02",
"subgrpname": "DWV PIPE - UP TO 150MM"
}, {
"effective_date": "01/02/2016",
"grp": "01",
"grpname": "STOPS/FLEX HOSES/COVER PLATES",
"id": "2",
"percent": "11",
"prodname": "PVC PIPE 100MM X 6MTR SWJ SN10",
"prodno": "1400201",
"subgrp": "03",
"subgrpname": "DIMPLEX BATHROOM ACCESSORIES"
}]
推荐答案
您的extractData(可能还有您的HTTP API)正在返回对象{}-ngFor需要数组[]进行迭代.
Your extractData (and possibly also your HTTP API) is returning an object {} - ngFor requires an array [] to iterate.
更改服务/API以产生一个数组,或转换组件中的对象.
Change your service/API to produce an array, or transform the object in your component.
这篇关于尝试在Angular中差异'[object Object]'时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!