LoginSignup
9
8

More than 5 years have passed since last update.

async pipeとは

Last updated at Posted at 2018-12-12

前提として

  • observableを学ばなければいけません。僕の過去記事を参照してください

async pipe

  • PromiseやObservableな非同期オブジェクトをそのままtemplateで表示できるもの
  • |をpipe関数という。

@Component({
  selector: 'async-pipe',
 //asyncでsubscribeの効力がある
  template: '<div>Time: {{ numberOne | async }}</div>'
})
export class AsyncPipeComponent {
 //1をメッセージとして、observableをcomponent内で作る
 // subssribeしないと、メッセージは普通取り出すことはできない。
  const numberOne$ = of(1); 
}
1

async pipeを使わなかった場合

  • ngOnDestroyのところで、subscribeされた後のobservableを停止(unsubscribe)しなければいけません。
import { Subscription } from 'rxjs';

...

export class App implements OnInit, OnDestroy {
  eventStream$: Observable<EventStream>
  subscription: Subscription;

  ngOnInit() {
      //subscribeしたものを変数にする。
    this.subscription = this.eventStream$.subscribe(...);
  }

  ngOnDestroy() {
    // コンポーネントを破棄する時にunsubscribeする
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}

async pipe使用のメリット

  • template側に役割を任せられるのでコードがスッキリする
  • コンポーネントが破棄される時に自動でunsubscribeする
  • ライフサイクルのon Pushの変更検知でのバグがない(subscribeだと検知されない)

引用

9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8