Angular 5如何处理带有Blob响应和JSON错误的HTTP Get请求

24

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

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

我只需要调用下载服务来触发:

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[]
  });
}

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

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

谢谢你的帮助。

6个回答

22

这是一个已知的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);
            })
        );
    }
}

在你的AppModule或CoreModule中声明它:

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

@NgModule({
    ...
    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: BlobErrorHttpInterceptor,
            multi: true
        },
    ],
    ...
export class CoreModule { }

2
应该是被接受的答案,完美的,可以复制/粘贴。 - Flyout91

4
对我来说,只是使用 FileReader 的建议不足够,因为它们与 HttpTestingController 不兼容(因为 blob 到 json 的转换是异步的)。在我的情况下,karma 测试总是在该 promise 解决之前完成。这意味着我无法使用这种方法编写测试不成功的路径的 karma 测试。我建议提出一种将 blob 同步转换为 json 的解决方案。
服务类:
public doGetCall(): void {
    this.httpClient.get('/my-endpoint', {observe: 'body', responseType: 'blob'}).subscribe(
        () => console.log('200 OK'),
        (error: HttpErrorResponse) => {
            const errorJson = JSON.parse(this.blobToString(error.error));
            ...
        });
}

private blobToString(blob): string {
    const url = URL.createObjectURL(blob);
    xmlRequest = new XMLHttpRequest();
    xmlRequest.open('GET', url, false);
    xmlRequest.send();
    URL.revokeObjectURL(url);
    return xmlRequest.responseText;
}

Angular测试:

it('test error case', () => {
    const response = new Blob([JSON.stringify({error-msg: 'get call failed'})]);

    myService.doGetCall();

    const req = httpTestingController.expectOne('/my-endpoint');
    expect(req.request.method).toBe('GET');
    req.flush(response, {status: 500, statusText: ''});
    ... // expect statements here
});

错误子句中解析的errorJson现在将包含{error-msg: 'get call failed'}

2

像大多数人一样,我希望我的错误消息是同步的。我通过将其放入警报框中来解决问题:

(err:any) => { 

    // Because result, including err.error, is a blob,
    // we must use FileReader to display it asynchronously:
    var reader = new FileReader();
    reader.onloadend = function(e) {
      alert("Error:\n" + (<any>e.target).result);
    }
    reader.readAsText(err.error);

    let errorMessage = "Error: " + err.status.toString() + " Error will display in alert box.";
    // your code here to display error messages.
},

1

0

此问题可通过在标头中添加'Content-Type':'application/json'来解决。


-1
响应应该是一个 Blob,但显然不是这样的。 为避免此错误,请将 responseType 从 blob 更改为 arraybuffer。
public executeDownload(id: string): Observable<Blob> {
  return this.http.get(this.replaceUrl('app/download', denunciaId), {responseType: 'arraybuffer'}).map(result => {
    return result;
  });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接