Angular 5 manage http get with blob response and json errors

时间:2018-03-25 19:19:50

标签: angular typescript http blob angular5

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:

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 HttpErrorResponse that contains in its error field an array of RemoteError. RemoteError is an interface that I wrote to manage remote errors.

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

Thanks in advance.

5 个答案:

答案 0 :(得分:2)

这是一个已知的Angular issue,在该线程中,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 { }

答案 1 :(得分: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.
},

答案 2 :(得分:1)

与文档一样,#34;从Blob读取内容的唯一方法是使用FileReader。&#34; https://developer.mozilla.org/en-US/docs/Web/API/Blob

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

答案 3 :(得分:0)

I haven't actually tried this, but I suspect that the following should work, since by default the error is an 'any':

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

public onDownload() {
  this.downloadService.executeDownload(this.id).subscribe(
   res: Blob  => {
     saveAs(res, 'file.pdf');
   }, 
   error: RemoteError[] => {
     console.log('TODO', error);
   });

}

答案 4 :(得分:-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;
  });
}