複数の非同期パイプを簡単にする方法


角度では、複数のオブザーバブルへの非常に一般的なsuscribeがテンプレートにデータを表示し、これらのオブザーバブルをテンプレートで使用します.

async pipe, make easy to subscribe and unsubscribe from the observable in our templates.


たとえば、我々のアプリは、ユーザー名と選手の統計情報を表示し、それぞれの別のAPIから来た.
  playerNumber = 237;
 player$ = this.nbaService.getPlayer(this.playerNumber);
  stats$ = this.nbaService.getStats(this.playerNumber);
テンプレートは次のようになります.
  <div *ngIf="player$ | async as player" class="player">
    <h2>{{ player.first_name }} {{ player.last_name }}</h2>
    <h3>Stats</h3>
    <ul *ngIf="stats$ | async as stats">
      <li *ngFor="let stat of stats.data">
        Points: {{ stat.pts }} Rebounds: {{ stat.reb }} Steals: {{ stat.stl }}
      </li>
    </ul>
  </div>
観察可能性を一つの観測可能なものに結合できるか
RXJSはcombineLatestを提供し、それぞれの観測可能な配列を返します.
CombineLatestは、すべての観測可能な1つの値が発生するまで、私たちは、プレーヤーの$と統計$ $値を表示するときに表示します.
プレイヤー$のような新しいオブザーバブルを作成します.
CombinelateTestから値をパイプし、マップでそれらをパイプで処理して、テンプレートで使用する各値についてきれいな名前を持つオブジェクトを返します.
  playerData$ = combineLatest([this.player$, this.stats$]).pipe(
    map(([info, stats]) => ({ info, stats }))
  );
PlayerData用のパイプを使用するテンプレートを更新し、NGIFと余分な非同期パイプを削除します.
<div class="container">
  <h1>Nba</h1>
  <div *ngIf="playerData$ | async as playerData">
    <h2>{{ playerData.info.first_name }} {{ playerData.info.last_name }}</h2>
    <h3>Stats</h3>
    <ul>
      <li *ngFor="let stat of playerData.stats.data">
        Points: {{ stat.pts }} Rebounds: {{ stat.reb }} Steals: {{ stat.stl }}
      </li>
    </ul>
  </div>
</div>
両方のサブスクリプションを管理するために1つの観測があります.組み合わせを使用してデータを結合して結合し、テンプレートを使用します.

第二編コードの改善


フィードバックのおかげで、コードを改善することができます.
  • は、presenttionalなコンポーネントユーザープロファイル
  • を使用する
  • アプリケーションコンポーネントをコンテナコンポーネントに変換し、観測可能なプロセスと処理データを処理します.
  • Read more about
    Read more about


    コンポーネントのプロファイル


    我々は、コンポーネントのプロパティを使用してデータを表示するには、コンポーネントのApp Playerの情報を作成します.
    import { Component, Input } from '@angular/core';
    
    @Component({
      selector: 'app-player-info',
      templateUrl: './player-info.component.html',
      styleUrls: ['./player-info.component.css'],
    })
    export class PlayerInfoComponent {
      @Input() name: string;
      @Input() stats: any;
    }
    
    アプリ.コンポーネントは、統計を簡素化するためにマップRXJS演算子を使用して観測可能なデータを処理します.破壊している単一のオブジェクトへのデータ配列.

    Read more about Rxjs map operator.
    Read more about destructuring object.


     stats$ = this.nbaService.getStats(this.playerNumber).pipe(
        map((value) => {
          return {
            ...value.data[0],
          };
        })
      );
    
    テンプレートを編集し、Playerプロファイルコンポーネントを使用してプロパティをバインドします.
    <div class="container">
      <h1>Nba</h1>
      <div *ngIf="playerData$ | async as player">
        <app-player-info
          [name]="player.info.first_name"
          [stats]="player.stats"
        ></app-player-info>
      </div>
    </div>
    
    我々のコードは、データを処理して、情報を示すことについての分離をします.
    demoでプレーしてください
    Unsplashの上でMichhaによる写真