angular - 无法显示来自 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 切换到单一的引用,一切正常。但我需要很多,所以我可以分配许多子类别并展示它们。
请帮我。
解决方案
无法读取未定义的属性“标题”
意味着您正在尝试访问title
未定义事物的属性。查看您的代码只能是这一行。
{{ category.fields.subCategories.fields.title }}
我假设这subCategories
是一个集合,因此是一个array
. Anarray
没有fields
属性(未定义)。这就是title
无法访问的原因——因为它是undefined
.
如果确实如此,并且它确实是一个集合,您可能希望再次遍历所有subCategories
以访问每个子类别的字段和标题。
推荐阅读
- swift - 如果允许重复点赞,在新的点赞条目替换旧点赞且不计入点赞数的情况下,如何将点赞数加 1?
- android - 如何将字符串从应用程序传递到另一个应用程序?
- solr - 如何授权一个 solr 用户使用 solr 7 的一个核心
- java - java中线程“main”中的异常。非常简单的代码,在它没有问题之前
- python - python Tkinter清除输出文本的某些标签
- arrays - Oracle如何在json数组列中查找包含某些值的行
- r - format() - 从星期一开始的几周?
- html - 使用 unpkg 在 html 中重用 Vue 组件
- javascript - React 状态从另一个状态变量(React Select)更新所有先前的元素
- javascript - 从数据库中获取 2 个计数器