angular - 在 Observable.create 中取消 HTTP 请求

标签 angular rxjs

我正在使用 Angular 2 rc3。

我有一个返回 rxjs Observable 的服务,其中有一些异步任务,然后是递归 HTTP 请求。这是分块上传,因此有多个顺序请求,每个请求都在前一个 block 的成功处理程序中触发。

我想知道如何在处理包含的 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();
}

我可以在网络面板中看到,在销毁组件后,上传进度仍在继续。

如何取消?

如果它有助于理解上传,那么我正在使用这个 https://github.com/kinstephen/angular-azure-blob-upload移植到 Angular 2

最佳答案

您需要在可观察创建回调中返回一个函数。调用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();
  }
}

关于angular - 在 Observable.create 中取消 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38188777/

相关文章:

angular - 函数在 debounceTime 后被多次调用

javascript - 与常规可观察对象相比,Angular HTTP 可观察对象的行为有所不同?

javascript - Angular 2 : Using Set? 浏览器兼容性和迭代不可能

angular - 当单击网格上的任何其他单元格时,Ag Grid 停止编辑单元格。如何防止这种情况?

javascript - rxjs/订阅没有导出成员 'Subscription'

Angular 8 HTTP 拦截器中断订阅

javascript - 登录表单无法将值推送到函数 onSubmit

data-binding - 绑定(bind)在 Angular2 模板中不起作用

javascript - 如何解决DELETE错误404未找到express.js

html - Bootstrap 网格添加在左侧和右侧有边距?