Learn AspNet
Learn AspNet

Reputation: 1612

Bypass if it has null values in angular

I am very new to Angular. Here is my function in a component that calls API and expects results but it can also result in errors.

 this.Service.callAPI().
      .subscribe(data => {
        if(data?.errors){
       });

It is failing because data and also errors can be null. It says cannot read the property of null. How can I fix this? I have tried data?.errors? but it does not work.

Upvotes: 1

Views: 567

Answers (2)

Sapna Kumari
Sapna Kumari

Reputation: 56

Question mark is used to check undefined or null values in html not in typescript files.

Replace your line if(data?.errors) with if(data && data.errors). It should work

Hope this fix your problem.

Upvotes: 1

Shumail
Shumail

Reputation: 3143

One approach can be to apply filter operator before subscribing and filter the null and undefined values.

Try this:

this.Service.callAPI().pipe(
  filter(data => data !== undefined && data !== null),
).subscribe(data => {
  if (data.errors) {
    // at this point, data won't be undefined or null
  }
})

Upvotes: 0

Related Questions