无法显示ContentfulAngular中参考许多内容类型的标题

问题描述

嘿,我有content_type类别,其中有两个字段-title和subcategory.Sub类别引用了很多选项,但是当我尝试显示所有子类别时,控制台出现错误“无法读取未定义的属性'title'”。我不知道为什么。

在我的content-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将引用切换为Single,则一切正常。但是我需要很多,所以我可以分配许多子类别并显示所有内容。

请帮助我。

解决方法

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

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

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

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

如果确实是这样,并且它确实是一个集合,您可能想在所有subCategories上进行迭代,以访问每个子类别的字段和标题。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...