首页 > 解决方案 > 使用 *ngfor IONIC 和 JSON 从对象内部的数组中检索对象

问题描述

我正在努力从嵌套在 json 文件中的对象中的数组中检索对象。

Json 文件是这样的:

    {
    "success": {
        "total": 1
    },
    "contents": {
        "quotes": [
            {
                "quote": "You can’t succeed coming to the potluck with only a fork.",
                "author": "Dave Liniger",
                "length": "64",
                "tags": [
                    "inspire",
                    "team-building",
                    "tso-funny",
                    "working-with-people"
                ],
                "category": "inspire",
                "title": "Inspiring Quote of the day",
                "date": "2018-05-05",
                "id": null
            }
        ],
        "copyright": "2017-19 theysaidso.com"
    }
}

我正在尝试检索嵌套在引号中的引号。

到目前为止,我一直在尝试这个:

    <ion-list>
<ion-item *ngFor="let c of contents"></ion-item>
<ion-item *ngFor="let q of c['quotes']">
    <h2>{{ q.quote }}</h2>
</ion-item>

但是我不断收到“无法获取未定义或空引用的'引号'的属性”

我究竟做错了什么?

标签: jsonionic-frameworknestedngfor

解决方案


你的代码应该是这样的:

    <ion-list>

    <ion-item *ngFor="let q of contents.quotes">
        <h2>{{ q.quote }}</h2>

    </ion-item>
    </ion-list>

有关嵌套ngFor,请参见以下示例

@Component({
  selector: 'ngfor-grouped-example',
  template: `
 <h4>NgFor (grouped)</h4>
 <ul *ngFor="let group of peopleByCountry"> 
   <li>{{ group.country }}</li>
   <ul>
    <li *ngFor="let person of group.people"> 
      {{ person.name }}
    </li>
   </ul>
 </ul>
 `
})
class NgForGroupedExampleComponent {

  peopleByCountry: any[] = [
    {
      'country': 'UK',
      'people': [
        {
          "name": "Douglas  Pace"
        },
        {
          "name": "Mcleod  Mueller"
        },
      ]
    },
    {
      'country': 'US',
      'people': [
        {
          "name": "Day  Meyers"
        },
        {
          "name": "Aguirre  Ellis"
        },
        {
          "name": "Cook  Tyson"
        }
      ]
    }
  ];
}

您还可以参考此链接了解更多详情: https ://codecraft.tv/courses/angular/built-in-directives/ngfor/


推荐阅读