を使用して別の観察可能
次に、Observable
を表示するために、angle2 async
パイプを使用します。ここで
は私のコードです:
import {Injectable} from "angular2/core";
import {Observable} from "rxjs/Observable";
import 'rxjs/Rx';
@Injectable()
export class AppService {
constructor() {
console.log('constructor', 'appService');
this.constructSomeObservable();
}
someObservable$:Observable <string[]>;
constructSomeObservable() {
this.someObservable$ = Observable.create(observer => {
const eventSource = new EventSource('/interval-sse-observable');
eventSource.onmessage = x => observer.next(JSON.parse(x.data));
eventSource.onerror = x => observer.error(console.log('EventSource failed'));
return() => {
eventSource.close();
};
});
this.someObservable$.subscribe(
theStrings=> {
console.log(theStrings);
//Somehow convert the plain array of strings to an observable and concat it to this.someObservable$ observable...
},
error=>console.log(error)
);
}
}
は誰でも助けてくださいことはできますか?
さらに、EventSourceが繰り返し呼び出されると、サービスインスタンスObservable<string[]>
が確実に更新されるようにしたいと思います。私の購読ロジックは正しい場所にありますか? angular2 async
パイプと一緒に
this.someObservable$.subscribe(
theStrings=> {
console.log(theStrings);
this.someObservable$ = this.someObservable$.concat(Observable.create(theStrings));
},
error=>console.log(error)
);
}
:
編集1は、次のように私はRxJS concat
演算子を使用しようとした
<ul>
<li *ngFor="#s of appService.someObservable$ | async">
a string: {{ s }}
</li>
</ul>
と何ページに表示されます。文字列はコンソールに表示されます...
何が間違っていますか?
編集2:アプリはgithubの上で利用可能であるhere
編集3:私はの利用だけでなく、サブスクライブするために、アカウントティエリーのアドバイスにasync
パイプの特に使用をとっていますスキャンオペレータ
ザ・唯一残っている問題は、今私はテンプレートにレンダリングする文字列のために、ルータのリンクをクリックする必要があること...テンプレートが自動的に更新されませんされています...
githubの上の参照プロジェクトと関連するタグ:https://github.com/balteo/demo-angular2-rxjs/tree/36864628/536299
おかげティエリー:
は、より多くの詳細については、この質問を参照してください!あなたが提案した非同期パイプと記事に関して、私は 'Observable'を持っています。それでOKです。残りのコードとプランナーについては、私は購読する必要はありません。どうして? –
balteo
よろしくお願いします!実際、 'async'パイプはあなたのために透過的に(そして購読を中止して)購読します;-) –
実際にはそれほど明白ではありません;-) https://github.com/angular/angular/blob/master/modules/angular2/srcを参照してください/ common/pipes/async_pipe。ts#L75 –