如何从Observable中止Ajax请求? [英] How to abort an Ajax request from an Observable?
问题描述
我的代码包含我用来将文件上传到我的PHP服务器的简单函数(嵌套在 RxJS / Observable中的
): xhr
请求
My code contains this simple function I'm using to upload files to my PHP server (there's an xhr
request nested in an RxJS/Observable
):
fileUpload(file: File): Observable<any> {
return new Observable( observer => {
let xhr:XMLHttpRequest = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next(<any>JSON.parse(xhr.response));
} else {
observer.error(xhr.response);
observer.complete();
}
}
};
xhr.open('POST', '__BACKEND__?action=file-upload', true);
var formData = new FormData();
formData.append('file', file, file.name);
xhr.send(formData);
});
}
它完全正常运行但现在我还想添加一些取消机械师。
It is completely functional but now I would also like to add some sort of a cancellation mechanic to it.
只是取消订阅Observable是行不通的,因为我需要以某种方式调用 xhr.abort()
或我通过大量上传浪费了宝贵的资源。
Just unsubscribing from the Observable won't work, because I need to somehow call xhr.abort()
or I waste precious resources with large uploads.
是否可以通过修改此代码来获得优雅的解决方案,或者我做错了因为我使用了 RxJS / Observable
执行此任务?
Is it possible to get an elegant solution by modifying this code or am I doing it wrong because I'm using an RxJS/Observable
for this task?
推荐答案
创建<$ c $时c> Observable 您可以通过返回订阅
或函数
来指定取消订阅行为构建器函数:
When you create an Observable
you can specify the unsubscribe behavior by returning a Subscription
or a function
from builder function:
fileUpload(file: File): Observable<any> {
return new Observable( observer => {
let xhr:XMLHttpRequest = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next(<any>JSON.parse(xhr.response));
observer.complete();
} else {
observer.error(xhr.response);
}
}
};
xhr.open('POST', '__BACKEND__?action=file-upload', true);
var formData = new FormData();
formData.append('file', file, file.name);
xhr.send(formData);
//Return the tear down logic.
//You may also want to check here that it has not already completed
//Since this gets called in all cases when the `Subscription` terminates
return () => xhr.abort();
});
}
这篇关于如何从Observable中止Ajax请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!