Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 RC 5 Attempting to Get and Display a PDF from a Server

I am trying to display a PDF that is generated from a server onto a view in my Angular 2 RC 5 project. Right now, the ASPNETCORE server is returning the object as an 'application/pdf' and the Angular client is trying to parse the response as a blob. However, I get the following error on the client side:

Error: The request body isn't either a blob or an array buffer

The code that I'm using to call the PDF server is essentially:

getHeaders() : Headers {
    var headers = new Headers({
        'responseType': 'application/blob'
    });
    return headers;
}

getBlob() {
    return this.http.get(uri, new RequestOptions({headers: this.getHeaders()}, body: "" }))
    .map(response => (<Response>response).blob());
}
like image 267
John Avatar asked Aug 24 '16 19:08

John


2 Answers

Try to set the responseType to Blob, it should work:

getBlob() {
return this.http.get(uri, {responseType: ResponseContentType.Blob})
.map(response => (<Response>response).blob());

}

like image 88
fleske Avatar answered Nov 15 '22 22:11

fleske


Work's for me :

Component :

downloadInvoice(invoice) {
  this.loading = true;
  this.invoiceDataService
  .downloadInvoice(invoice)
  .subscribe(
    (blob) => {
      FileSaver.saveAs(blob, 'test.pdf');
    },
    error => this.error = error,
    () =>  {
      this.loading = false;
      console.log('downloadInvoices : Request Complete')
    }
  )
}

Data service :

downloadInvoice(invoice): Observable<Blob> {
  return this.api.downloadInvoice(invoice);
}

Api service :

downloadInvoice(invoice: Invoice):  Observable<Blob> {
  return this.authHttp
  .get(this.apiBase + '/invoices/' + invoice.hashid + '/download', {responseType: ResponseContentType.Blob})
  .map(response => {
    return new Blob([response.blob()], {type: 'application/pdf'});
  })
  .catch(this.handleError.bind(this));
}

Enjoy :)

like image 31
Mikhaël Gerbet Avatar answered Nov 15 '22 22:11

Mikhaël Gerbet