Angular 2 RC 5 Attempt to get and display a PDF file from the server

I am trying to display a PDF file created from the server for viewing in my Angular 2 RC 5 project. Right now, the ASPNETCORE server returns the object as "application / pdf" and the Angular client is trying to parse the answer as blob. However, on the client side, the following error occurs:

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

The code I use to invoke 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()); } 
+8
angular pdf asp.net-core blob
source share
2 answers

Try setting responseType to Blob, it should work:

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

}

+17
source share

Work with 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 :)

+1
source share

All Articles