2016-07-04 23 views
4

私は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

答えて

9

に移植され、このhttps://github.com/kinstephen/angular-azure-blob-uploadを使用している、アップロードを理解するのに役立ちます。 disposeメソッドを呼び出すときに呼び出される関数です。

return Observable.create((observer) => { 
    (...) 

    return() => { 
    // code to dispose/cancel things 
    }; 
}); 

uploadFileInChunksメソッド内でリクエストをキャンセルするには、サブスクリプションを保存し、そのunsuscribeメソッドを呼び出す必要があります。

reader.onloadend = (event) => { 
    // THIS IS THE REQUEST I WANT TO CANCEL 
    this.subscription = 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); 

     }); 
}; 

() => { 
    if (this.subscription) { 
    this.subscription.unsubscribe(); 
    } 
} 
+0

私は返品機能を忘れました - ありがとうございました! 元の観測で 'dispose'を呼び出すとエラーが出ました。そこには' unsubscribe'もありました –

+1

FYI:disposeはrxjs4、unsubscribeはrxjs5です。 –

関連する問題