2017-04-10 47 views
2

我有一个JSON工作使用JSON angular2

json: string = `{ 
      "name" : "John", 
      "surname" : "Walsh", 
      "age" : "23" 
    }`; 

,我需要表现出来表

<table width="700"> 
      <caption>All Users</caption> 
      <thead> 
       <tr> 
        <th>name</th> 
        <th>surname</th> 
        <th>age</th> 
       </tr> 
      </thead> 
      <tbody> 
       <tr> 
        <td *ngFor="let names of users"></td> 
         {{ names}} 
       </tr> 
      </tbody> 
     </table> 

我试着这样做:

users = JSON.parse(this.json); 

,但得到的错误:

错误:无法找到不同的支持类型'John'的对象'[object Object]'。 NgFor仅支持绑定到阵列等阵元。

然后我试图转换用户数组是这样的:

arr:Array<{key: string, value: string}> = []; 
constructor(){ 
    for (var key in this.users) { 
     if (this.users.hasOwnProperty(key)) { 
     this.arr.push({ key: key, value: this.users[key] }); 
     } 
} 
} 

,但我不能老是用它遍历NgFor

回答

5

首先,你需要纠正你的用户的数组这样的:

users = [{ 
     "name" : "John", 
     "surname" : "Walsh", 
     "age" : "23" 
},{ 
     "name" : "Mike", 
     "surname" : "Mikic", 
     "age" : "25" 
}]; 

在同一时间,你应该迭代,并创建一个新的行中的每个你传递一个对象时:

<table width="700"> 
    <caption>All Users</caption> 
    <thead> 
     <tr> 
      <th>name</th> 
      <th>surname</th> 
      <th>age</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr *ngFor="let user of users"> 
      <td> 
        {{user.name}} 
      </td> 
      <td> 
        {{user.surname}} 
      </td> 
      <td> 
        {{user.age}} 
      </td> 
     </tr> 
    </tbody> 
</table> 
+0

真的问题出在我的JSON视图。 –

1
<tr *ngFor="let names of users"> 
    <td > {{ names.name}}</td> 
    <td > {{ names.sername}}</td> 
    <td > {{ names.age}}</td>   
</tr>