我有一个在生命周期事件ngOnChanges
上发生的函数,现在该函数正常工作但是当应用程序第一次加载时它会抛出错误ERROR TypeError: Cannot read property 'fields' of undefined
现在我知道原因是因为它尝试的数据从尚未到达的地方读取该物业,但很明显,当数据存在时,它有效..这是我的功能
ngOnChanges(changes: SimpleChanges) {
this.contentfulService.getWeekItems(this.item.fields.week)
.then((weekItems) => {
this.weekItems = weekItems;
}).then(() => {
this.numberOfItems = this.weekItems.length;
});
}
现在我知道如果我在component.html
我可以做这样的事情...... "item?.fields?..."
你的.ts
文件中是否有相应的内容?
答案 0 :(得分:2)
还没有打字稿中的Null合并运算符。请参阅:https://github.com/Microsoft/TypeScript/issues/16
然而,
this.item?.fields
相当于this.item && this.item.fields