Angular 5 使用 blob 响应和 json 错误管理 http get

xce*_*sco 16 blob http typescript angular angular5

我正在开发一个 Angular 5 应用程序。我必须从我的后端应用程序下载一个文件,为此我只需调用如下函数:

public executeDownload(id: string): Observable<Blob> {
  return this.http.get(this.replaceUrl('app/download', denunciaId), {responseType: 'blob'}).map(result => {
    return result;
  });
}
Run Code Online (Sandbox Code Playgroud)

并调用我刚刚调用的下载服务:

public onDownload() {
  this.downloadService.executeDownload(this.id).subscribe(res => {
    saveAs(res, 'file.pdf');
  }, (error) => {
    console.log('TODO', error);
    // error.error is a Blob but i need to manage it as RemoteError[]
  });
}
Run Code Online (Sandbox Code Playgroud)

当后端应用程序处于特定状态时,它不会返回 Blob,而是返回一个HttpErrorResponse在其error字段中包含RemoteError 数组的对象。RemoteError 是我编写的用于管理远程错误的接口。

在 catch 函数中,error.error 是一个 Blob。如何将 Blob 属性转换为RemoteError[]?

提前致谢。

Mar*_*rio 15

这是一个已知的Angular 问题,在该线程中 JaapMosselman 提供了一个非常好的解决方案,该解决方案涉及创建一个HttpInterceptor将 Blob 转换回 JSON 的方法。

使用这种方法,您不必在整个应用程序中进行转换,当问题解决后,您只需将其删除即可。

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class BlobErrorHttpInterceptor implements HttpInterceptor {
    public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
            catchError(err => {
                if (err instanceof HttpErrorResponse && err.error instanceof Blob && err.error.type === "application/json") {
                    // https://github.com/angular/angular/issues/19888
                    // When request of type Blob, the error is also in Blob instead of object of the json data
                    return new Promise<any>((resolve, reject) => {
                        let reader = new FileReader();
                        reader.onload = (e: Event) => {
                            try {
                                const errmsg = JSON.parse((<any>e.target).result);
                                reject(new HttpErrorResponse({
                                    error: errmsg,
                                    headers: err.headers,
                                    status: err.status,
                                    statusText: err.statusText,
                                    url: err.url
                                }));
                            } catch (e) {
                                reject(err);
                            }
                        };
                        reader.onerror = (e) => {
                            reject(err);
                        };
                        reader.readAsText(err.error);
                    });
                }
                return throwError(err);
            })
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

在你的 AppModule 或 CoreModule 中声明它:

import { HTTP_INTERCEPTORS } from '@angular/common/http';
...

@NgModule({
    ...
    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: BlobErrorHttpInterceptor,
            multi: true
        },
    ],
    ...
export class CoreModule { }
Run Code Online (Sandbox Code Playgroud)

  • 应该是公认的答案,完美,复制/粘贴。 (2认同)

Vay*_*rex 1

正如文档中“从 Blob 读取内容的唯一方法是使用 FileReader”。https://developer.mozilla.org/en-US/docs/Web/API/Blob

编辑:如果您需要 Blob 的一部分,您可以执行切片,返回新的 Blob,然后使用文件读取器。