私はAngular 2 rc3を使用しています。Observable.create内のHTTPリクエストをキャンセルします。
私はrxjs Observableを返すサービスを持っていますが、その中にはいくつかの非同期タスクがあり、再帰的なHTTPリクエストがあります。これはチャンクアップロードです。そのため、前のチャンクの成功ハンドラでトリガされた複数の順次リクエストがあります。
Observableを含むものを処分するときに内部HTTPリクエストをキャンセルする方法を知りたいと思います。
これは私が(本物ではないコードを)やっている基本的には次のとおりです。
// UploadService
upload (file) {
return Observable.create((observer) => {
let reader = new FileReader();
// convert file into chunks
let chunkedFile = this.chunkFile(file);
reader.onloadend = (event) => {
// THIS IS THE REQUEST I WANT TO CANCEL
this.http.put('url/to/upload/to', chunkedFile.currentChunk)
.subscribe((res) => {
// emit some data using containing observable, e.g. progress info
observer.next(res);
// trigger upload of next chunk
this.uploadFileInChunks(reader, chunkedFile, observer);
});
};
// this triggers the onloadend handler above
this.uploadFileInChunks(reader, chunkedFile, observer);
});
}
そして私はこのように私のコンポーネントでそれを使用します。
// ExampleComponent
upload() {
this.uploader = this.uploadService.upload(file)
.subscribe((res) => {
// do some stuff, e.g. display the upload progress
})
}
ngOnDestroy() {
// when the component is destroyed, dispose of the observable
this.uploader.dispose();
}
私がネットワークに見ることができますコンポーネントを破棄した後、アップロードの進行状況は引き続き続きます。
どうすればキャンセルできますか?
それは、私はあなたが観測作成コールバック内の関数を返す必要が角度2
私は返品機能を忘れました - ありがとうございました! 元の観測で 'dispose'を呼び出すとエラーが出ました。そこには' unsubscribe'もありました –
FYI:disposeはrxjs4、unsubscribeはrxjs5です。 –