Sandeep Gupta
Sandeep Gupta

Reputation: 7250

How to use multiple as keyword in an ngIf expression?

I have a note$ Observable in my component as follows:

this.note$ = this.serverService.makeGetReq({url:"some_url"})

note$ is of type Observable<{body:INote, errorCode:string}>

In my template:

<div class="container" *ngIf="(note$|async).body as note">...</div>

But I am getting follwing error when note$ resolves to null:

ERROR TypeError: Cannot read property 'body' of null

To avoid above error, I did following:

<div class="container" *ngIf="(note$|async) as value &&  value.body as note">...</div>

But I got an error:

ng: TypeError: Cannot read property 'toUpperCase' of undefined

My guess is, this is an unhelpful error message cause by using two as keywords in the same expression

How to avoid this error?

Upvotes: 1

Views: 429

Answers (2)

Sajeetharan
Sajeetharan

Reputation: 222552

You should use safe navigation operator in this case to handle null even though you are using async on the notes$. however i do not think body is needed.

  <div class="container" *ngIf="(note$|async)?.body as note">...</div>

this should be it,

<div *ngIf="note$| async as notes" class="notes-zone" >

Upvotes: 1

Ren&#233; Winkler
Ren&#233; Winkler

Reputation: 7058

  <div class="container" *ngIf="(note$|async)?.body as note">...</div>

Upvotes: 4

Related Questions