我正在开发一个项目,使用Angular4从API获取数据并使用* ngFor来呈现数据表。因为我还有更多具有相同结构的aip,我想使用(key,value)对来显示它们。在AngularJS中,我已经正确地呈现了这样的表:
<!--This is Good in AngularJS-->
<table>
<thead>
<tr>
<th ng-repeat="(key, value) in data.items[0]"> {{key}}
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat ="data in data.items >
<td ng-repeat="(key,value) in data">{{ value }}</td>
</tr>
</tbody>
</table>
但是,该表未正确显示在Angular4中。来自API的原始json数据显示为:
{
items: [
{
status: "Sold - Payment Received",
count: 30,
loans: 8,
dl_loans: 8,
avg_available: 149.5,
min: 28,
max: 346,
principal: 13452.37,
closed: 0,
chrg_of_balance: 0,
final_balance: 0
},
{
status: "At Auction - Awaiting Info",
count: 4,
loans: 4,
dl_loans: 4,
avg_available: 70.45,
min: 36,
max: 102,
principal: 11727.8,
closed: 0,
chrg_of_balance: 0,
final_balance: 0
},
...
}
这是我的app.component.ts:
ngOnInit(): void {
this.dataService.getData().subscribe(
(data) => {
this.data = data.items;
this.titles = data.items[0];
}
);
}
我为过滤器键和值创建了一个pip.ts:
import { PipeTransform, Pipe } from '@angular/core';
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
return keys;
}
}
在Angular4 HTML中:
<!--This is Bad in Angular4-->
<table>
<thead align="center">
<tr>
<th *ngFor = "let item of titles | keys">
{{item.key}}
</th>
</tr>
</thead>
<tbody>
<tr>
<td *ngFor = "let item of data | keys ">
{{item.value | json }}
</td>
</tr>
</tbody>
</table>
然而,UI中的thead显示正常,但tbody部分显示包括整个对象(部分):
status
---------------------------------------
{
status: "Sold - Payment Received",
count: 30,
loans: 8,
dl_loans: 8,
avg_available: 149.5,
min: 28,
max: 346,
principal: 13452.37,
closed: 0,
chrg_of_balance: 0,
final_balance: 0
}
--------------------------------------
任何人都知道如何才能正确呈现此表格?先谢谢你了!
答案 0 :(得分:7)
使用不同的管道而不是您正在使用的管道只返回对象的键
import { PipeTransform, Pipe } from '@angular/core';
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push(key);
}
return keys;
}
}
您应该将模板代码更改为
<thead align="center">
<tr>
<th *ngFor = "let item of titles | keys">
{{item}}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor = "let item of data ">
<td *ngFor = "let key of item | keys " >
{{item[key]}}
</td>
</tr>
</tbody>
这应该可以解决问题