首页 > 解决方案 > 无法显示来自 Contentful (Angular) 的参考(许多)内容类型的标题

问题描述

嘿,我有包含两个字段的 content_type 类别 - 标题和子类别。子类别是带有许多选项的参考,但是当我尝试显示所有子类别时,我在控制台中出现错误“无法读取未定义的属性'标题'”。我想不通为什么。

在我的内容 API 服务中,我有:

getCategory(query?: object): Promise<EntryCollection<Category>> {
return this.clientApi.getEntries<Category>(
  Object.assign({}, query, { content_type: 'categories', include: 2})
);

}

之后在我的 component.ts 文件中我有:

export class Component implements OnInit {

  categories: Array<Entry<Category>>;

  constructor(private contentfulApiService: ContentfulApiService) { }

  ngOnInit(): void {

    this.contentfulApiService
      .getCategory()
      .then((categories) => (this.categories = categories.items));
  }
}

在我的 component.html 中:

  <ul>
    <li *ngFor="let category of categories">
      {{ category.fields.subCategories.fields.title }}
    </li>
  </ul>

如果我从 Contentful 切换到单一的引用,一切正常。但我需要很多,所以我可以分配许多子类别并展示它们。

请帮我。

标签: angulartypescriptreferenceone-to-manycontentful

解决方案


无法读取未定义的属性“标题”

意味着您正在尝试访问title未定义事物的属性。查看您的代码只能是这一行。

{{ category.fields.subCategories.fields.title }}

我假设这subCategories是一个集合,因此是一个array. Anarray没有fields属性(未定义)。这就是title无法访问的原因——因为它是undefined.

如果确实如此,并且它确实是一个集合,您可能希望再次遍历所有subCategories以访问每个子类别的字段和标题。


推荐阅读