首页 > 解决方案 > 在这种情况下,如何使用 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行为如此呢?ObservableloadImageFilethrowError

我相信我的问题是我已经在里面了,而它应该new Observable是主要功能。loadImageFilereturn throwError

我该如何克服呢?

PS:请忽略此文本:StackOverflow 不会让我发布此内容,因为它主要是代码,但在这种情况下,我相信它是有道理的,所以我在这里写这一段是为了使帖子验证通过 :)

谢谢!

标签: rxjs

解决方案


这是解决方案:

observer.error(xhr)


推荐阅读