正如您在主题中看到的那样,我收到此错误是因为数据库中的一列是一串 JSON,我想我可以通过在 ngFor 循环中使用 ngFor 循环来解决这个问题。
以下是html:
<tbody>
<tr *ngFor="let item of mf.data">
<td>{{ item.id }}</td>
<td>{{ item.user_id }}</td>
<td class="text-right">{{ item.orders_id }}</td>
<td>
<ul *ngFor="let x of item.product">
<li>{{ x.name }}</li>
<li>{{ x.price }}</li>
<li>{{ x.category }}</li>
<li>{{ x.ts }}</li>
<li>{{ x.enabled }}</li>
<li>{{ x.counter }}</li>
</ul>
</td>
</tr>
</tbody>
Run Code Online (Sandbox Code Playgroud)
以下是“产品”列的一行的样子:
[
{
"id": "13",
"name": "test 5",
"price": "3.42",
"category": "chocolates",
"ts": "2019-01-08 10:41:15",
"product_image_id": "50",
"enabled": "1",
"product_image": "40-64-grand-canyon.png",
"counter": "2"
},
{
"id": "18",
"name": "test 4 post dubs",
"price": "6.72",
"category": "chocolates",
"ts": "2019-01-08 08:55:49",
"product_image_id": "36",
"enabled": "1",
"product_image": "first-ent-rent-ridgegate.png",
"counter": "3"
},
{
"id": "9",
"name": "something test 3 upd",
"price": "12.23",
"category": "chocolates",
"ts": "2019-01-08 08:54:49",
"product_image_id": "29",
"enabled": "1",
"product_image": "80-44-grand-canyon.png",
"counter": "2"
}
]
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我尝试了以下操作,没有错误,但也没有显示任何内容:
<tbody>
<tr *ngFor="let item of mf.data">
<td>{{ item.id }}</td>
<td>{{ item.user_id }}</td>
<td class="text-right">{{ item.orders_id }}</td>
<td>
<ul *ngFor="let x of mf.data.product">
<li>{{ x.name }}</li>
<li>{{ x.price }}</li>
<li>{{ x.category }}</li>
<li>{{ x.ts }}</li>
<li>{{ x.enabled }}</li>
<li>{{ x.counter }}</li>
</ul>
</td>
</tr>
</tbody>
Run Code Online (Sandbox Code Playgroud)
随着尝试以下,但未定义产品的错误:
<tbody>
<tr *ngFor="let item of mf.data">
<td>{{ item.id }}</td>
<td>{{ item.user_id }}</td>
<td class="text-right">{{ item.orders_id }}</td>
<td>
<ul *ngFor="let x of mf.data[i].product; let i = index">
<li>{{ x.name }}</li>
<li>{{ x.price }}</li>
<li>{{ x.category }}</li>
<li>{{ x.ts }}</li>
<li>{{ x.enabled }}</li>
<li>{{ x.counter }}</li>
</ul>
</td>
</tr>
</tbody>
Run Code Online (Sandbox Code Playgroud)
提前致谢
这是因为product对象未与其他给定数据一起转换为 JSON,因为它是嵌套对象。
在您的模板中,调用将product字符串转换为JSON 对象的方法
<ul *ngFor="let x of convertToJSON(item.product)">
Run Code Online (Sandbox Code Playgroud)
在您的组件中创建一个方法,如下所示
convertToJSON(product: any) {
return JSON.parse(product);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5418 次 |
| 最近记录: |