【问题标题】:Retrieving an object from an array inside an object using *ngfor IONIC and JSON使用 *ngfor IONIC 和 JSON 从对象内部的数组中检索对象
【发布时间】:2018-05-06 08:49:12
【问题描述】:

我正在努力从嵌套在 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>

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

我做错了什么?

【问题讨论】:

  • 使用ngFor不能直接访问json文件的内容
  • 什么意思?
  • 我确实有访问权限。我正在使用提供商 'quote.ts' 。这会将 json 的内容返回给我
  • 您正试图访问 ngFor 范围之外的 c

    {{ q.quote }}

  • 那么如何访问“contents”中的数组“quotes”?

标签: json ionic-framework nested ngfor


【解决方案1】:

你的代码应该是这样的:

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

【讨论】:

  • 感谢您的回复。我试过这个,但我得到“找不到一个不同的支持对象'(对象对象)'类型'对象'NgFor只支持绑定到可迭代对象,如数组?
  • 试试这个我已经更新了答案,我错过了内容是你的json中的一个对象
  • 谢谢。我得到“无法获取未定义或空引用的属性'引号'?
  • 你能分享你的控制器代码吗,你有没有将你的响应分配给任何变量?
  • 它不会让我,太多的字符。我在 home.ts(quotes: string[]) 中声明了一个引号字符串数组。然后这是我的 quote.ts @Injectable() export class QuoteProvider { constructor(public http: HttpClient) { console.log('Hello QuoteProvider Provider'); } getQuote(): Observable { return this.http.get("quotes.rest/qod.json"); } }
猜你喜欢
  • 2016-08-01
  • 1970-01-01
  • 2018-08-13
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多