如何通过* ngFor在角度2打字稿前端显示json数组

时间:2018-01-13 06:09:11

标签: json angular typescript ngfor

下面是angular2简单的前端页面::

       <table class="table">
          <tr>
              <th>title</th>
              <th>description</th>
          </tr>
          <tr *ngFor="let notes of Note">
              <td>{{notes.title}}</td>
              <td>{{notes.body}}</td>
          </tr>
      </table>

下面是组件代码::其中Note有

export class Note {
  noteId:  number ; 
  title:  String ;
  body: String ;    
  color:  String ;
  isArchive:  boolean ; 
  isPinned:  boolean ; 
  isTrash: boolean ;
}



notes:Note[]=[];

ngOnInit() {
  this.getAllNotes();
}
//get all anotes
getAllNotes(){
this.noteService.getNotes()
.subscribe(
 // notes => {   //tried not working
 //   this.notes = notes;
 // console.log(notes) },
data => {
  console.log("notes get");
  console.log(data._body);
  this.notes=data._body;
  console.log("notes array");
  console.log(this.notes);
},
error => {
  console.log("notes error");
    console.log(error);

});
}

在this.notes输出上面是::

[
  {
    "noteId": 5,
    "title": "hi ",
    "body": "ragini",
    "color": null,
    "createDate": 1515820245951,
    "lastUpdated": 1515820245951,
    "reminder": null,
    "image": null,
    "collaborator": [],
    "labels": [],
    "user": 1,
    "archive": false,
    "pinned": false,
    "trash": false
  },
  {
    "noteId": 8,
    "title": "s",
    "body": null,
    "color": null,
    "createDate": 1515820746348,
    "lastUpdated": 1515820746348,
    "reminder": null,
    "image": null,
    "collaborator": [],
    "labels": [],
    "user": 1,
    "archive": false,
    "pinned": false,
    "trash": false
  }
]

现在如何在angular2前端显示这些数据。

2 个答案:

答案 0 :(得分:1)

您需要使用 notes 而不是 Note

<tr *ngFor="let note of notes">
    <td>{{note?.title}}</td>
    <td>{{note?.body}}</td>
</tr>

<强> DEMO

答案 1 :(得分:1)

Html代码::

<tr *ngFor="let notes of notes; let i = index">
    <td>{{notes.title}}</td>
    <td>{{notes.body}}</td>
</tr>

我刚做了这个.notes = JSON.parse(data._body);剩余代码如上所述。

data => {
    console.log(data._body);
    this.notes=JSON.parse(data._body); // parsing here
    console.log("notes array"+this.title);
    console.log("Title :: "+this.notes.title);
},