I'm learning Angular 2 Beta. I wonder how to download the PDF file from the API and display it in my view? I've tried to make a request using the following:
var headers = new Headers();
headers.append('Accept', 'application/pdf');
var options = new ResponseOptions({
headers: headers
});
var response = new Response(options);
this.http.get(this.setUrl(endpoint), response).map(res => res.arrayBuffer()).subscribe(r=>{
console.log(r);
})
- Please note that I only use the
console.log
to see the value ofr
But I always get the following exception message:
"arrayBuffer()" method not implemented on Response superclass
Is it because that method isn't ready yet in Angular 2 Beta? Or is there any mistake that I made?
Any help would be appreciated. Thank you very much.
In fact, this feature isn't implemented yet in the HTTP support.
As a workaround, you need to extend the
BrowserXhr
class of Angular2 as described below to set theresponseType
toblob
on the underlying xhr object:Then you need to wrap the response payload into a
Blob
object and use the FileSaver library to open the download dialog:The FileSaver library must be included into your HTML file:
See this plunkr: http://plnkr.co/edit/tfpS9k2YOO1bMgXBky5Y?p=preview
Unfortunately this will set the
responseType
for all AJAX requests. To be able to set the value of this property, there are more updates to do in theXHRConnection
andHttp
classes.As references see these links:
Edit
After thinking a bit more, I think that you could leverage hierarchical injectors and configure this provider only at the level of the component that executes the download:
This override would only applies for this component (don't forget to remove the corresponding provide when bootstrapping your application). The download component could be used like that:
To get Filesaver working in Angular 5: Install
In your component use
import * as FileSaver from "file-saver";
and use FileSaver.default and not FileSaver.SaveAs