2017-02-16 16 views
3

イム一度に観察が終了したシンプルなコールバックを実装しようと、ここに私のコードは次のとおりです。Angular2観察可能なコールバック

ngOnInit() { 
    this.propertyService 
    .getProperties() 
    .subscribe(
     (data: ContentPropertyModel[]) => this.properties = data 
    ); 
    this.status = 'active'; 
} 

状態が観察できるの実行前に変更されるが。どのように私はobservableが実行された後this.statusを変更することができます上の任意のアイデア?あなたのハンドラを購読する

答えて

4

移動this.status

ngOnInit() { 
    this.propertyService 
    .getProperties() 
    .subscribe(
     (data: ContentPropertyModel[]) => { 
      this.properties = data 
      this.status = 'active'; 
     } 
    ); 
} 
+0

ありがとうございます - それは完璧に働いた – rhysclay

2

購読3つの引数(OnNext機能、誤差関数、関数の完了)になります。

各項目が受信された後にコードを実行して実行する場合は、最初の関数引数にコードを記述します。ストリームの完了後に実行したい場合は、最後の関数の引数に記述します。

ngOnInit() { 
    this.propertyService 
    .getProperties() 
    .subscribe(
     (data: ContentPropertyModel[]) => { 
      this.properties = data 
     }, 
     (err) => console.log(err), 
     () => this.status = 'active' 
    ); 
} 

このリンクhttp://reactivex.io/documentation/observable.htmlを参照してください。

また、onError()およびCompleted()関数はDOMイベントでは機能しません。

+0

非常に包括的な答えをありがとう – rhysclay

1

はい、別の回答で指摘されているように、subscribeハンドラ内にstatusと設定する必要があります。しかし、これはまた、観察可能物がその最初のアイテムを放出するまで、statusが全く設定されないことを意味する。私はあなたが

STATUS IS {{status$ | async}} 

にステータスを表示したり、表示が観察されるまでwaitingになり、あなたのテンプレートで今

this.status$ = this.propertyService.getProperties() 
    .startWith(false) 
    .map(b => b ? 'active' : 'waiting'); 

ようなもので成し遂げることができ、自身statusが観察することの代替としてお勧めしたいです最初に発砲する。あなたはイベントハンドラでstatusの現在の値にアクセスする必要がなければならない場合は、観察と、同じようにpropertiesを扱う場合

、あなたは、

logStatus() { 
    this.status$.take(1).subscribe(s => console.log("status is", s); 
} 

でそうすることができる

ngOnInit() { 
    this.properties$ = this.propertyService.getProperties(); 
    this.status$ = this.properties$.startWith(false).map(b => b ? 'active' : 'waiting'); 
} 

あなたはngOnInitの登録をすべて避けることができます。これは覚えておいてからngOnDestroyに取り壊す必要があります。