小编Mar*_*siv的帖子

使用json angular2

我有一个JSON

json: string = `{
          "name" : "John",
          "surname" : "Walsh",
          "age" : "23"
    }`;
Run Code Online (Sandbox Code Playgroud)

我需要在表格中显示它

<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>
Run Code Online (Sandbox Code Playgroud)

我试着这样做:

users = JSON.parse(this.json);
Run Code Online (Sandbox Code Playgroud)

但得到一个错误:

错误:无法找到"John"类型的不同支持对象"[object Object]".NgFor仅支持绑定到诸如Arrays之类的Iterables.

然后我尝试将用户转换为数组,如下所示:

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] });
      }
 }
}
Run Code Online (Sandbox Code Playgroud)

但我不能用它来迭代它NgFor.

typescript angular

2
推荐指数
1
解决办法
98
查看次数

标签 统计

angular ×1

typescript ×1