DEV Community

Discussion on: How to simplify multiple async pipes

Collapse
 
layzee profile image
Lars Gyrup Brink Nielsen

Hey Dany! 👋

What if we used a presentational component that didn't deal with observables at all? A container component could deal with those pesky observables 😃 What if we used RxAngular Template to avoid the AsyncPipe null defect and NgIf hack? 🤔

@Component({
  // (...)
  selector: 'nba-player',
  template: `
    <h1>Nba</h1>

    <h2>{{ info?.first_name }} {{ info?.last_name }}</h2>

    <h3>Stats</h3>

    <ul>
      <li *ngFor="let stat of stats">
        Points: {{ stat.pts }} Rebounds: {{ stat.reb }} Steals: {{ stat.stl }}
      </li>
    </ul>
  `,
})
export class PlayerComponent {
  @Input()
  info: PlayerInfo | null = null;
  @Input()
  stats: PlayerStats = [];
}
Enter fullscreen mode Exit fullscreen mode
@Component({
  // (...)
  template: `
    <!-- Using RxAngular PushPipe to avoid null -->
    <nba-player
      [info]="info$ | push"
      [stats]="stats$ | push"
    ></nba-player>

    <!-- Or: Using RxAngular LetDirective to conditionally render
      when observables have resolved and avoid null -->
    <ng-container *rxLet="info$ as info">
      <nba-player *rxLet="stast$ as stats"
        [info]="info"
        [stats]="stats"
      ></nba-player>
    </ng-container>
  `,
})
export class PlayerContainerComponent {
  #playerNumber = 237;

  info$ = this.nbaService.getPlayer(this.#playerNumber);
  stats$ = this.nbaService.getStats(this.#playerNumber);

  constructor(private nbaService: NbaService) {}
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
danywalls profile image
Dany Paredes

Amazing refactor, wide better I need read again you article about presentation container and embrace it :P
dev.to/this-is-angular/container-c...
and dev.to/this-is-angular/presentatio...

Collapse
 
layzee profile image
Lars Gyrup Brink Nielsen

There's no one best way 🙂 But it's good to have alternatives.

Thread Thread
 
danywalls profile image
Dany Paredes • Edited

Updated with you feedback :D