gremo
gremo

Reputation: 48459

How to avoid multiple async pipes with the same Observable source in Angular?

My component has an Observable named state$: how can I avoid repeat myself when I need to access state$.favorites, like the example below?

@Component({
  selector: 'app-example',
  template: `
    <ng-container *ngIf="(state$ | async).favorites.length">
      {{ (state$ | async).favorites.length }}
    </ng-container>
  `,
})
export class ExampleComponent() {
  @Select(state => state.app) state$: Observable<AppState>;
}

Is there any way to assign it to a template variable?

Upvotes: 2

Views: 1462

Answers (1)

Patricio Vargas
Patricio Vargas

Reputation: 5522

You can do the following:

 <ng-container *ngIf="(state$ | async) as state">
      {{ state.favorites.length }}
  </ng-container>

You don't need to check for .length. By doing what I did, you are checking if the observable has arrived and checking if the value is not null.

Upvotes: 3

Related Questions