我从GET REST调用收到以下JSON对象。
[
{
"driverName": "Bob",
"customerName": "-",
"status": "AVAILABLE"
},
{
"driverName": "Harry",
"customerName": "-",
"status": "AVAILABLE"
},
{
"driverName": "Peter",
"customerName": "-",
"status": "AVAILABLE"
},
{
"driverName": "John",
"customerName": "-",
"status": "AVAILABLE"
},
{
"driverName": "Rob",
"customerName": "-",
"status": "AVAILABLE"
}
我想迭代这个并以表格格式显示它们。 我的代码如下所示。
AppComponent.ts
driverStatusResponse: any[] = [];
AppService.ts
getDriverStatus():Observable<any>{
var httpUrl = this.baseURL+"driverstatus/";
return this._http.get(httpUrl)
.pipe(map((response: Response) => <any> response.text()));
}
组件的html:
<tbody bgcolor="#b3ecff">
<tr *ngFor="let driver of driverStatusResponse">
<td>{{driver.driverName}}</td>
<td>{{driver.customerName}}</td>
<td>{{driver.status}}</td>
</tr>
</tbody>
我在控制台中收到错误如下:
AppComponent.html:24 ERROR Error: Error trying to diff '[{"driverName":"Bob","customerName":"kushhs","status":"BUSY"},{"driverName":"Harry","customerName":"aSdjb","status":"BUSY"},{"driverName":"Peter","customerName":"aSdjb","status":"BUSY"},{"driverName":"John","customerName":"zdgf","status":"BUSY"},{"driverName":"Rob","customerName":"asdfsg","status":"BUSY"}]'. Only arrays and iterables are allowed
at DefaultIterableDiffer.push../node_modules/@angular/core/fesm5/core.js.DefaultIterableDiffer.diff (core.js:6194)
at NgForOf.push../node_modules/@angular/common/fesm5/common.js.NgForOf.ngDoCheck (common.js:3386)
at checkAndUpdateDirectiveInline (core.js:10100)
at checkAndUpdateNodeInline (core.js:11363)
at checkAndUpdateNode (core.js:11325)
at debugCheckAndUpdateNode (core.js:11962)
at debugCheckDirectivesFn (core.js:11922)
at Object.eval [as updateDirectives] (AppComponent.html:35)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:11914)
at checkAndUpdateView (core.js:11307)
请帮我解决这个问题。
答案 0 :(得分:0)
可能你的HTTP API正在返回一个对象{} - ngFor需要一个array []来迭代。
更改API以生成数组,或转换组件中的对象。
看看API响应是否以{}开头。
<强> OBJECT 强>
{[
{
driverName: "John",
customerName: "-",
status: "AVAILABLE"
}
]}
<强> ARRAY 强>
[{
driverName: "John",
customerName: "-",
status: "AVAILABLE"
}]
答案 1 :(得分:0)
在用代码尝试不同的东西后,我找到了答案。 错误在于服务电话。提供正确数组迭代的修改后的代码是
getDriverStatus():Observable<any[]>{
var httpUrl = this.baseURL+"driverstatus/";
return this._http.get(httpUrl)
.pipe(map((response: Response) => <any[]> response.json()));
}
这将响应体提供为json数组。