Search code examples
angulartypescripthttpblobangular5

Angular 5 manage http get with blob response and json errors


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.


Solution

  • 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.

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