Smokey Dawson
Smokey Dawson

Reputation: 9230

ngOnChanges causing error until async function is complete Angular 5

I have a function that happens on the lifecycle event ngOnChanges, now the function works fine but when the app first loads it throws an error ERROR TypeError: Cannot read property 'fields' of undefined now I know the reason is because the data its trying to read the property from hasn't arrived yet but then obviously when the data is there it works.. this is my function

 ngOnChanges(changes: SimpleChanges) {
    this.contentfulService.getWeekItems(this.item.fields.week)
      .then((weekItems) => {
        this.weekItems = weekItems;
      }).then(() => {
        this.numberOfItems = this.weekItems.length;
  });
 }

now I know if I was in my component.html I could do something like this.. "item?.fields?..." is there an equivalent for inside your .ts file?

Upvotes: 0

Views: 431

Answers (1)

gawicks
gawicks

Reputation: 1964

There is no Null coalescing operator in typescript yet. Refer: https://github.com/Microsoft/TypeScript/issues/16

However,

this.item?.fields is equivalent to this.item && this.item.fields

Upvotes: 2

Related Questions