我正在使用 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/