Reputation: 1011
I have the below code to download the JSON object from url. But the download is not happening.
openDownloadWindow() {
this.downloadPdf().subscribe(pdfBlob => {
const url = window.URL.createObjectURL(pdfBlob);
window.open(url);
});
}
public downloadPdf() {
const url = 'http://161.202.31.51:8185/sgdocsrv/ar/getARList';
const headers = new Headers();
headers.append('Authorization', 'JWT ' + localStorage.getItem('id_token'));
return this.http.get(url, { headers: headers, responseType: ResponseContentType.Blob }).map(
(res) => {
return new Blob([res.blob()], { type: 'application/pdf' });
});
}
Upvotes: 1
Views: 1188
Reputation: 2536
there's a bunch of things to change so here's what I had working :
public getMeMyPDF(): any {
const url = 'http://161.202.31.51:8185/sgdocsrv/ar/getARList';
this.PDF = this.http.get(url, {
observe: 'response',
headers: new HttpHeaders({'Content-Type', 'application/pdf', 'Authorization',
'JWT ' + localStorage.getItem('id_token')}),
responseType: 'text' as 'text' // <-- this part is rediculous but necessary
}).catch(this.handleError);
return this.PDF;
}
I personally had it in a post request but get is obviously the more common and obvious scenario.
I finally stumbled upon this in a long github issue on angular.
the double trick was to have a cast from text to text and to have your whole options inside the http call as dirty as that may look.
I also threw in my syntax where I first declared a var and returned that (not necessarily a waste of a line if suddenly you need to console log it again), and also added a catch which you can handle in a global catch function for all your APIs.
Don't forget to like, favorite and subscribe to your api, wherever you call it. (even if you don't do anything inside the subscribe (in your case you will))
here's what I did back in my component that calls my apiservice.getMeMyPDF :
getMeAPDF(){
this.apiService.getMeMyPDF().subscribe(res => {
if(res !== null && res !== undefined){
this.saveToFileSystem(res.body);
}
}, (error) => console.log(error), () => {});
}
private saveToFileSystem(response) {
const blob = new Blob([response], { type: 'text/pdf' });
const d = new Date();
saveAs(blob, 'WOWPDF_' + this._datepipe.transform(d, 'yyyyMMdd_HHmmss') + '.pdf');
}
Upvotes: 1
Reputation: 2279
You need to create a new function that subscribes to your downloadPdf
function and opens a link to the blob
:
openDownloadWindow() {
this.downloadPdf().subscribe(pdfBlob => {
const url = window.URL.createObjectURL(pdfBlob);
window.open(url);
});
}
Upvotes: 0