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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49479959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:18:19  来源:igfitidea点击:

Angular 5 manage http get with blob response and json errors

angulartypescripthttpblobangular5

提问by xcesco

I'm working on an Angular 5 application. I have to download a file from my backend-application and to do this I simply invoke a function like this:

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

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

And to invoke the download service I just invoke:

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

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

When the backend application is in a particular state, instead of returning a Blob, it returns an HttpErrorResponsethat contains in its errorfield an array of RemoteError. RemoteError is an interface that I wrote to manage remote errors.

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

In catch function, error.error is a Blob. How can I translate Blob attribute into an array of RemoteError[]?

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

Thanks in advance.

提前致谢。

采纳答案by Vayrex

As in docs "The only way to read content from a Blob is to use a FileReader." https://developer.mozilla.org/en-US/docs/Web/API/Blob.

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

EDIT: If you need part of blob, you can do a slice, which returns new Blob, and then use file reader.

编辑:如果你需要 blob 的一部分,你可以做一个切片,它返回新的 Blob,然后使用文件阅读器。

回答by Marcos Dimitrio

This is a known Angular issue, and in that thread JaapMosselman provides a very nice solution that involves creating an HttpInterceptorwhich will translate the Blob back to JSON.

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

Using this approach, you don't have to do conversions throughout your application, and when the issue is fixed, you can simply remove it.

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

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

Declare it in your AppModule or CoreModule:

在你的 AppModule 或 CoreModule 中声明它:

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

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