如何使用angular 6在html中显示动态json数据?

时间:2018-08-07 04:48:07

标签: html angular angular6

我的网络服务返回如下的json数据。

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

现在,我需要以表格格式显示它。通常,在jquery中,我曾经动态创建表,并将div ID分配给表,然后将其替换为动态创建的表。

我的component.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中该如何显示?

3 个答案:

答案 0 :(得分:2)

您应该将表格布局放在html模板中,而仅将获取和分配数据的逻辑放在打字稿代码中。
HTML模板:

<table>
  <thead>
    <tr>
      <td>Key</td>
      <td>Record Id</td>
      <td>Record Name</td>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let item of content">
      <td>{{item.Key}}</td>
      <td>{{item.Record.id}}</td>
      <td>{{item.Record.name}}</td>
    </tr>
  </tbody>
</table>

答案 1 :(得分:1)

在这里您可以使用 ngFor Directive在表中动态加载JSON数据 .component.html

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

*。component.ts

sample:any= [{ "Key" : "001",
  "Record" : {"id":"001",
               "name" : "qwerty"}
},
{ "Key" : "003",
  "Record" : {"id":"003",
               "name" : "asdfg"}
}];

答案 2 :(得分:1)

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>