【发布时间】:2016-03-13 00:14:47
【问题描述】:
我正在尝试从 Angular 2 应用程序中提供 pdf 下载...
此代码有效:
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);
但我希望使用 Angular 2 的内置 Http 客户端。
一点研究:
- 在发布时未编写的角度文档: https://angular.io/docs/js/latest/api/http/ResponseTypes-enum.html
- 不确定这是否适用,但 rxjs responseType 参数似乎 仅包含文本和 json: https://github.com/Reactive-Extensions/RxJS-DOM/blob/master/doc/operators/ajax.md
还有一些测试代码:
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。 saveAs 函数来自这里:https://github.com/eligrey/FileSaver.js
【问题讨论】:
-
似乎 blob() 方法尚未实现。见github.com/angular/angular/blob/master/modules/angular2/src/…。可以在此处找到跟踪实施状态的问题:github.com/angular/angular/issues/2803
-
您到底是如何让“saveAs”工作的?我已经安装了模块,安装了打字,当我运行它时仍然得到“没有这样的功能:saveAs”......太烦人了......你如何将它包含在打字稿代码中? (我用的是webpack,还没弄明白)
-
我刚刚忽略了来自 TS 编译器的错误。它仍然编译...马虎啊?