0
votes

I am very new to Angular and I have the following doubt about this piece of code.

In a view I have this code:

<li *ngFor="let hero of heroes$ | async" >
  <a routerLink="/detail/{{hero.id}}">
    {{hero.name}}
  </a>
</li>

iterating on heroes$. This is not an array but it is an Observable because it is working on this property of the related component:

heroes$: Observable<Hero[]>;

This is not completly clear to me.

Following my interpretation (please confirm or refute).

  • The *ngFor can't directly iterate on the heroes$ because it is an Observable.

  • This Observable emit an array of Hero but this is an asyncronous behavior.

  • The async pipe is something thath subscribe this Observable and when it is ready (when emit the array) the *ngFor directive can iterate on this array.

In practice in this way I can do this operation directly into the view instead to do it in the component subscribing the Observable.

1
Your assumption is correct.user184994
The async pipe also unsubscribes automatically when the component is destroyed, as mentioned in the documentation.ConnorsFan

1 Answers

2
votes

If you write it this way then it is more clear: (heroes$ | async) as heroList