Angular:在将JSON数组转换为HTML表时动态查找头文件



在Angular中,我想把一个JSON数组转换成一个HTML表。

我看到了一个关于AngularJS的老答案:

<table>
<thead>
<tr>
<th ng-repeat="(key, value) in records[0]">{{key}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(key, value) in records">
<td ng-repeat="(key, value) in value">
{{value}}
</td>
</tr>
</tbody>
</table>

JSON是这样的:

[{
"Name": "Alfreds Futterkiste",
"City": "Berlin",
"Country": "Germany"
}, {
"Name": "Berglunds snabbköp",
"City": "Luleå",
"Country": "Sweden"
}, {
"Name": "Centro comercial Moctezuma",
"City": "México D.F.",
"Country": "Mexico"
}]

我试着把它翻译成Angular的语法。以下是我目前得到的结果:

<table>
<thead>
<tr>
<th *ngFor="let item of records[0]  | keyvalue">{{item.key}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of records">
<td *ngFor="let item1 of item | keyvalue">
{{item1.value}}
</td>
</tr>
</tbody>
</table>

现在编译失败,因为records[0]是未定义的…我如何将这个表达式转换为较新的语法(或创建等效的东西)?

更新1:

我有一个部分解。但是,对于这种部分解决方案,呈现的表与旧的AngularJS呈现并不完全相同(因为它创建了多个不必要的头行,其中只有一个被填充,而旧的呈现中只有一个头行)。

<table style="border-collapse: collapse;">
<thead *ngFor="let item of records; let last=last">
<tr *ngIf="last">
<th *ngFor="let item1 of item | keyvalue">
{{item1.key}}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of records">
<td *ngFor="let item1 of item | keyvalue">
{{item1.value}}
</td>
</tr>
</tbody>
</table>

你有更好的方法来做到这一点,可能类似于旧的AngularJS版本?

更新2:

在Angular中,我通过一个来自Angular的请求来访问JSON数据,然后这个请求被重定向到一个后端服务。该服务可以读取文件,或者从数据库中获取数据。当后端服务准备好数据后,它会将数据返回给Angular请求。Angular端代码如下:

HTML:
<div>
<h3>Test Post Request</h3>
<button (click)="postData()">Click Me</button>
<div>Response: {{records}}</div>
</div>
TypeScript:
private dataPostTestUrl = '/api/postTest';
records: string | undefined;
public postData(): void {
this.appService.sendData().subscribe((data: any) => {
this.records = data.content;
});
}
public sendData(): Observable<any> {
return this.http.post(this.dataPostTestUrl, {});
}

我想你可能需要在组件中定义records

records = [{
"Name": "Alfreds Futterkiste",
"City": "Berlin",
"Country": "Germany"
}, {
"Name": "Berglunds snabbköp",
"City": "Luleå",
"Country": "Sweden"
}, {
"Name": "Centro comercial Moctezuma",
"City": "México D.F.",
"Country": "Mexico"
}];

我很确定这就是你需要的:https://stackblitz.com/edit/angular-ivy-n7irpw?file=src/app/hello.component.ts

看看我是如何在app.component.ts中导入文件的以及我如何在HTML中循环。

如果有帮助,请告诉我!

最新更新