Async pipe does not fill object data into template

后端 未结 5 1255
遇见更好的自我
遇见更好的自我 2021-02-01 17:41

Can anyone help me see if there is a syntax error here in my template? It does not give error, but does not fill in data into the template either:

5条回答
  •  说谎
    说谎 (楼主)
    2021-02-01 18:06

    Objects are a bit tricky with the async pipe. With an Observable that contains an array, we can use NgFor and create a local template variable (hero below) that gets assigned each item of the array after the async pipe extracts the array from the Observable. We can then use that variable elsewhere in the template:

    {{hero.name}}

    But with an Observable that contains a single object, I'm not aware of any way to create a local template variable that will reference that object. Instead, we need to do something more complicated:

    {{(hero | async)?.name}}

    And we would need to repeat that for each property of the object we want to display. (The above line assumes that component property hero is an Observable.)

    It is probably easier to assign the object (that is inside the Observable, hero$ below) to a property of the component, using component logic:

    this._heroService.hero$.subscribe(data => this.hero = data.json());
    

    and then use NgIf or the Elvis/safe navigation operator to display the data in the view:

    {{hero.name}}
    {{hero?.name}}

提交回复
热议问题