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.
Here is the simplest way to download a file from an API that I was able to come up with.
Call the
downloadFile(api,fileName)
method from your component class.To get FileSaver run the following commands in your terminal
Here is the code that works for downloadign the API respone in IE and chrome/safari. Here response variable is API response.
Note: http call from client needs to support blob response.
Working solution with C# Web API loading PDF as a byte array:
C# loads PDF as a byte array and converts to Base64 encoded string
Angular service gets PDF
Component view embeds the PDF via binding to service response
The
pdfSource
variable below is the returned value from the service.See the Angular DomSanitizer docs for more info.
I don't think all of these hacks are necessary. I just did a quick test with the standard http service in angular 2.0, and it worked as expected.
So here is how I managed to get it to work. My situation: I needed to download a PDF from my API endpoint, and save the result as a PDF in the browser.
To support file-saving in all browsers, I used the FileSaver.js module.
I created a component that takes the ID of the file to download as parameter. The component, , is called like this:
The component itself uses XHR to fetch/save the file with the number given in the no parameter. This way we can circumvent the fact that the Angular2 http module doesn't yet support binary result types.
And now, without further ado, the component code:
I've used Font Awesome for the fonts used in the template. I wanted the component to display a download button and a spinner while the pdf is fetched.
Also, notice I could use require to fetch the fileSaver.js module. This is because I'm using WebPack so I can require/import like I want. Your syntax might be different depending of your build tool.
Hello, here is a working example. It is also suitable for PDF! application/octet-stream - general type. Controller:
Angular2:
Service xhr:
Install file-saver npm packages "file-saver": "^1.3.3", "@types/file-saver": "0.0.0" and include in vendor.ts import 'file-saver';
Component btn download.
Using