rxjs - 在这种情况下,如何使用 rxjs Observable 抛出错误?
问题描述
我有这样的代码:
loadImageFile(url: string, progressCallback: (progress: number) => void): Observable<string> {
return new Observable<string>(observer => {
const xhr = new XMLHttpRequest();
const nativeWindow = this.windowRef.nativeWindow;
let notifiedNotComputable = false;
xhr.open("GET", url, true);
xhr.responseType = "arraybuffer";
xhr.onprogress = event => {
if (event.lengthComputable) {
const progress: number = (event.loaded / event.total) * 100;
progressCallback(progress);
} else {
if (!notifiedNotComputable) {
notifiedNotComputable = true;
progressCallback(-1);
}
}
};
xhr.onloadend = function() {
if (!xhr.status.toString().match(/^2/)) {
// Here I want that the user of the Observable created at the top with
// "return new Observable" can use "pipe(catchError(...))".
}
if (!notifiedNotComputable) {
progressCallback(100);
}
const options: any = {};
const headers = xhr.getAllResponseHeaders();
const m = headers.match(/^Content-Type:\s*(.*?)$/im);
if (m && m[1]) {
options.type = m[1];
}
const blob = new Blob([this.response], options);
observer.next((nativeWindow as any).URL.createObjectURL(blob));
observer.complete();
};
xhr.send();
});
}
我怎样才能使这种方法返回的xhr.onloadend
行为如此呢?Observable
loadImageFile
throwError
我相信我的问题是我已经在里面了,而它应该new Observable
是主要功能。loadImageFile
return throwError
我该如何克服呢?
PS:请忽略此文本:StackOverflow 不会让我发布此内容,因为它主要是代码,但在这种情况下,我相信它是有道理的,所以我在这里写这一段是为了使帖子验证通过 :)
谢谢!
解决方案
这是解决方案:
observer.error(xhr)
推荐阅读
- git - 配置 gitlab 以将 ssh 上传到自定义目录和 apache
- asp.net - 如何让 Swashbuckle 生成带有日期(没有时间)的 Swagger 属性?
- r - 运行 2 个绘图命令后调用 Par(NEW=True) 而不绘图
- amazon-web-services - 初次注册后如何在 Deeplens 相机中启用 SSH
- rest - 用于获取不同文件类型格式的 json 数据的 Restful API URL
- angularjs - 测试是否在 Service 中调用了私有方法
- angularjs - UI-Router-Breadcrumbs Angular JS
- java - 找不到从谷歌驱动API下载的文档,它在哪里?
- c - 我在 C 中的函数没有打印值
- keyboard - Telegram-Bot ReplyKeyboardMarkup 为每个成员显示在组中