问题描述
嘿,我有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
是一个集合,因此是array
。 array
将没有fields
属性(未定义)。这就是无法访问title
的原因-因为它是undefined
。
如果确实是这样,并且它确实是一个集合,您可能想在所有subCategories
上进行迭代,以访问每个子类别的字段和标题。