使用json angular2

时间:2017-04-10 19:14:43

标签: angular typescript

我有一个JSON

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);

但收到了错误:

错误:无法找到不同的支持对象&#39; [object Object]&#39;类型&#39; John&#39;。 NgFor仅支持绑定到Iterables,例如Arrays。

然后我尝试将用户转换为这样的数组:

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迭代它。

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:1)

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