バックエンドから15秒ごとにデータを取得するとします。私のコードは次のようになります。Angular2保留中のリクエストがあるときにHTTP要求をキューに入れないようにする
TestComponent:
public ngOnInit(): void {
Observable.timer(0, 15000).subscribe(() => {
this.callService();
});
}
private callService(): void {
this.testService.callBackendService().subscribe(data => {
this.data = data;
});
}
TestService:
public callBackendSerivce(): Subscribable<Data> {
return this.http.get(this.serviceUrl)
.map(this.extractData)
.catch(this.handleError);
}
問題は、バックエンドで何らかのエラーが発生したときの処理時間がより多くかかるということです
15秒後に、このコードはバックエンドサービスに再度アクセスし、再び応答を待つことはありません。私はそのような行動を防ぎ、以前の電話からの応答を受け取ったときにだけ電話をかけたい。これを実装する方法は?
私はそれは次のようになります考えた:これを行うに任意のより良い解決策はあり
- :
TestComponent:
public ngOnInit(): void { this.callService(); } private callService(): void { this.testService.callBackendService().subscribe(data => { this.data = data; this.subscribeToService(); }); } private subscribeToService(): void { this.timerSubscription= Observable.timer(15000).subscribe(() => { this.callService(); this.timerSubscription.unsubscribe(); }); }
2つの質問?
いいえ - Observable.timerに最初の結果を取得して自動的に退会する方法はありますか?このコードを追加することはできません:
this.timerSubscription.unsubscribe();
で
retry
オペレータをチェックしてください。あなたの例では、保留中のリクエストがある場合、私はこのリクエストをキャンセルして新しいコールを行います。これは私が探しているものではありません。 – Toma