Cancel HTTP request inside Observable.create

I am using Angular 2 rc3.

I have a service that returns an rxjs Observable, inside which there are some asynchronous tasks, and then a recursive HTTP request. This is a fragmented load, so there are several consecutive requests, each of which is launched in the success handler of the previous fragment.

I would like to know how to cancel an internal HTTP request when I have a containing Observable.

This is basically what I am doing (not real code):

// 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);
    });
}

And then I use it in my component as follows:

// 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();
}

I see on the network panel that after the destruction of the component, the download process continues.

How can i cancel it?

, https://github.com/kinstephen/angular-azure-blob-upload Angular 2

+4
1

. 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();
  }
}
+9

All Articles