首页 > 解决方案 > 如何使用 Angular 6 在 html 中显示动态 json 数据?

问题描述

我的网络服务返回一个 json 数据,如下所示。

 [{ "Key" : 001,
   "Record" : {"id":"001",
                "name" : "qwerty"}
 },
 { "Key" : 003,
   "Record" : {"id":"003",
                "name" : "asdfg"}
 }]

现在我需要以表格格式显示它。通常在jquery中我用来动态创建一个表并将一个div id分配给一个表,然后用动态创建的表替换它。

我的组件.ts:

 export class CatComponent extends Lifecycle {

constructor(
    private $modal: $ModalManagerService,
    private http: HttpClient
) {
    super();
}

_initialize(): void {
        this.http.get('http://127.0.0.1:3000/query/aa',{responseType:"json"}).subscribe(
   response => {
     console.log("data :"+response);
     var sample=JSON.stringify(response);
     });
}

}

$("#divv").html(content);

在角度 6 中我应该如何显示?

标签: htmlangularangular6

解决方案


TS

export class CatComponent extends OnInit{
public data: any;

    constructor(
        private $modal: $ModalManagerService,
        private http: HttpClient

    ) {
        super();
    }

    ngOnInit(): void {
        this.http.get('http://127.0.0.1:3000/query/aa',{responseType:"json"}).subscribe(
        response => {
            this.data = response;
            console.log("data :"+response);
            var sample=JSON.stringify(response);
       });
    }
}

HTML

<table>
  <thead>
    <tr>
      <td>Key</td>
      <td>ID</td>
      <td>Name</td>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor ="let d of data;">
      <td>{{d.Key}}</td>
      <td>{{d.Record.id}}</td>
      <td>{{d.Record.name}}</td>
    </tr>
  </tbody>
</table>

推荐阅读