Reputation: 1612
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
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
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