ngOnChanges导致错误,直到异步功能完成Angular 5

时间:2018-03-22 06:17:45

标签: angular typescript angular5

我有一个在生命周期事件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文件中是否有相应的内容?

1 个答案:

答案 0 :(得分:2)

还没有打字稿中的Null合并运算符。请参阅:https://github.com/Microsoft/TypeScript/issues/16

然而,

this.item?.fields相当于this.item && this.item.fields