首页 > 解决方案 > Angular *NgFor 将数组中的字符串迭代到表 TD 标记

问题描述

我创建了一个从后端检索 JSON 数据的角度页面。

Json 输出的格式如下

fields  
0   "count"
1   "Date"
2   "Status"
rows    
0   "["2","2019-11-21","Operate"]"
1   "["3","2019-12-12","Maintain"]"
________________________________________________

{
    "fields":
        ["count","Date","Status"],
    "rows":
        [
            "["2","2019-11-21","Operate"]",
            "["3","2019-12-12","Maintain"]"
        ],
    "id":
        0
}

我想在前端创建一个表格,使用字段中的值作为标题,将行中的值作为单元格。例如

_____________________________
| count |   Date   | Status |
|---------------------------|
|   2   |2019-11-21| Operate|
|   3   |2019-12-12|Maintain|
-----------------------------

但是,当调用数据时,我得到了这些结果

| count                       |   Date   | Status |
|-------------------------------------------------|
|["2","2019-11-21","Operate"] |          |        |
|["3","2019-12-12","Maintain"]|          |        |
---------------------------------------------------

我的表格html代码如下

<table class="table table-borderless table-striped table-hover" *ngIf="appDetail?.fields">
    <thead>
        <th *ngFor="let field of appDetail.fields" class="table-header">{{field}}</th>
    </thead>
    <tbody>
        <tr *ngFor="let row of appDetail.rows">
            <td *ngFor="let item of row">{{item}}</td>
        </tr>
    </tbody>
</table>

我的模特

export class AppDetail {
    public fields: string[];
    public rows: string[][];
}

我的组件

public getSealData() {

    this.sealidService.getSplunkData(this.idValue).subscribe(data => {
      this.appDetail = data as AppDetail;

      console.log(data.fields);
      console.log(data.rows);

    })

  }

编辑 现在我在之间进行迭代,我在控制台中收到以下错误消息

ERROR Error: Cannot find a differ supporting object of type String

我假设这与我的模型有关?

编辑 原来我没有得到一个数组数组,而是一个字符串数组。看起来正在进行一些解码,但实际的 JSON 看起来更像这样

"fields": 
    ["count","Date","Status"],
 "rows": 
    ["[\"2\",\"2019-11-21\",\"Operate\"]", "[\"3\",\"2019-12-12\",\"Maintain\"]"],

所以我得到的错误是由于字符串值不可迭代。Console.log 输出 console.log(data.rows)

0: "["2","2019-11-21","Operate"]"
1: "["2","2019-12-02","Maintain"]"

已解决 - 我将不得不与后端数据的所有者合作,以获得适用于 Saurabh 答案的正确格式。

标签: javajsonangular

解决方案


工作演示

你可以这样做:迭代行,行元素本身是数组,而不是再次迭代那些要渲染的元素td

<tbody>
   <tr *ngFor="let row of appDetail.rows">
      <td *ngFor="let item of row">{{item}}</td>
   </tr>
</tbody>

推荐阅读