首页 > 解决方案 > Angular 6 错误:找不到“字符串”类型的不同支持对象

问题描述

正如您在主题中看到的那样,我收到此错误是因为数据库中的一列是 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>

以下是“产品”列的一行的样子:

 [
  {
    "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"
  }
]

顺便说一句,我尝试了以下方法,没有错误,但也没有任何显示:

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

除了尝试以下,但未定义产品错误:

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

提前致谢

标签: jsonangular6

解决方案


这是因为product对象未与其他给定数据一起转换为 JSON,因为它是嵌套对象。

在您的模板中,调用将product字符串转换为JSON 对象的方法

<ul *ngFor="let x of convertToJSON(item.product)">

在您的组件中创建一个方法,如下所示

convertToJSON(product: any) {
    return JSON.parse(product);
}

推荐阅读