代码之家  ›  专栏  ›  技术社区  ›  Sandeep Gupta

如何在ngif表达式中使用multiple as关键字?

  •  0
  • Sandeep Gupta  · 技术社区  · 6 年前

    我有一个 note$ Observable 在我的组件中,如下所示:

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

    注释$ 属于类型 Observable<{body:INote, errorCode:string}>

    在我的模板中:

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

    但当我在 注释$ 决心解决 null :

    ERROR TypeError: Cannot read property 'body' of null
    

    为了避免上述错误,我执行了以下操作:

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

    但我有一个错误:

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

    我的猜测是,这是一个无用的错误消息,使用两个 as 同一表达式中的关键字

    如何避免这个错误?

    2 回复  |  直到 6 年前
        1
  •  3
  •   René Winkler    6 年前
      <div class="container" *ngIf="(note$|async)?.body as note">...</div>
    
        2
  •  1
  •   Sajeetharan    6 年前

    safe navigation operator

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

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