I'm trying to provide a pdf download from within an angular 2 app...
this code works:
var reportPost = 'variable=lsdkjf';
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost/a2/pdf.php", true);
xhr.responseType = 'blob';
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == 4 && xhr.status == 200) {
var blob = new Blob([this.response], {type: 'application/pdf'});
saveAs(blob, "Report.pdf");
}
}
xhr.send(reportPost);
but i would have liked to use angular 2's built-in Http client.
a little research:
and some test code:
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post('http://localhost/a2/pdf.php', reportPost, {
headers: headers
})
.retry(3)
// .map( (res:any) => res.blob() ) // errors out
.subscribe(
(dataReceived:any) => {
var blob = new Blob([dataReceived._body], {type: 'application/pdf'});
saveAs(blob, "Report.pdf");
},
(err:any) => this.logError(err),
() => console.log('Complete')
);
ps. the saveAs function comes from here: https://github.com/eligrey/FileSaver.js
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…