0

I get the above error while I am getting some Data from api. This error if the data is null, if the api returns some data then this error is not coming.

I am using the below piece of code and subscribing the service.

this.systemMessageService.getSystemMessage().
        subscribe(res => {
            if (res.message !== null && res.message !== undefined) {
                this.systemMessage = res.message;
            } else {
                this.systemMessage = undefined;
            }
        });

Please help me how I can handle this error

R. Richards
  • 24,603
  • 10
  • 64
  • 64
  • replace `if (res.message !== null && res.message !== undefined)` with `if (res?.message)`. The issue is that the "res" variable can be null/undefined and this change will resolve it – The Fabio Jan 23 '22 at 21:07

2 Answers2

0

You should add also res to your if statement, e. g. if (res && res.mesage) or in shorter way if (res?.message){...} else {...}

Mateusz Ścigała
  • 186
  • 1
  • 1
  • 5
0

You're immediately trying to access the property message of the res variable without checking if res is defined. I'd propose to change the condition to one of the following

Option 1: double-bang operator !! + ternary operator ?:

this.systemMessage = (!!res && !!res.message) ? res.message : undefined;

The message property will only be accessed if res is defined.

About double-bang operator from here: "Converts Object to boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, true".

We could also use the ternary operator ?: to simplify the if-else to a single statement.

Option 2: optional chaining operator ?.

this.systemMessage = res?.message;

Essentially the same as option #1, but using the optional chaining operator ?.. Again, the message property will only be accessed if res is defined.

Importantly, from the docs, "instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined". So you could skip explicitly assigning the undefined.

Option 3: Nullish coalescing operator ??

this.systemMessage = res.message ?? undefined;

The nullish coalescing operator ?? returns the value of LHS (res.message) if it's defined or the value of RHS (undefined in your case) if it's LHS is nullish.

ruth
  • 29,535
  • 4
  • 30
  • 57