问题
As you can see by the subject, I am receiving this error because one of the columns in the database is a string of JSON and I thought I could get around this by having an ngFor loop within an ngFor loop.
The following is the 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>
The following is what one row of the column "product" looks like:
[
{
"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"
}
]
BTW, I have tried the following, with no errors, but nothing displays as well:
<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>
Along with trying the following, but errors of product not being defined:
<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>
Thanks in advance
回答1:
In your template call the method to convert product
string to JSON object
<ul *ngFor="let x of ConvertToJSON (item.product)">
Create a method in your ts file
ConvertToJSON(product: any) {
return JSON.parse(product);
}
回答2:
change your code like this.
<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">
<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>
Use *ngFor="let x of item" insted of *ngFor="let x of item.product"
来源:https://stackoverflow.com/questions/54174435/angular-6-error-cannot-find-a-differ-supporting-object-of-type-string