我正在使用Angular 4.3.2和新的HttpClient下载一个作为流发送的文件,并且我需要获取标题(特别是Content-Disposition),但它们似乎并没有出现在响应中尽管我可以在Chrome的开发工具中看到标题正确地与请求一起发送。使用Angular的新HttpClient,订阅事件时如何获取所有头文件?
这是代码:
downloadDocument(documentId: number) {
const downloadDocumentUrl = `${ this.config.apiUrls.documents }/${ documentId }`;
const downloadRequest = new HttpRequest('GET', downloadDocumentUrl, {
reportProgress: true,
responseType: 'blob'
});
let percentageDownloaded = 0;
this.http.request(downloadRequest).subscribe(
(event: HttpEvent <any>) => {
if (event) {
switch (event.type) {
case HttpEventType.ResponseHeader:
const contentDispositionHeader = event.headers.get('Content-Disposition');
console.log(contentDispositionHeader); // Always null here although I expected it to be there.
break;
case HttpEventType.DownloadProgress:
if (event.total) {
percentageDownloaded = Math.round((event.loaded/event.total) * 100);
}
break;
case HttpEventType.Response:
const downloadedFile: Blob = event.body;
fileSaverSaveAs(downloadedFile, `${ documentId }.pdf`, true); // This is where I'd like to use content-disposition to use the actual file name.
break;
}
}
,
(err) => {}
);
}
当这段代码被调用时,Chrome在开发工具下的响应首部网络标签报道:
访问控制允许的凭据:真
Access-Control-Allow-Origin:http://localhost:4200
Content-Disposition:attachment;文件名= doc5619362.pdf;文件名* = UTF-8''doc5619362.pdf
的Content-Length:88379
内容类型:应用程序/ PDF
日期:星期四,2017年8月3日9时43分41秒GMT
服务器:红隼
因人而异:Origin
X-Powered-By:ASP.NET
关于如何访问响应中的所有头文件的任何想法?这不仅仅是Content-Disposition不存在,除Content-Type之外的所有其他标题都不存在。
谢谢!
UPDATE
这里是一个工作Plunker演示该问题:https://plnkr.co/edit/UXZuhWYKHrqZCZkUapgC?p=preview
'event.headers.get(...)来读取响应的正文。 )'是正确的方法 –
正如Maximus建议的那样; doc:https://angular.io/api/http/Response#headers –
@ManhLe这个链接是用于旧的'Http'文档,OP使用新的'HttpClient',因此与文档的正确链接是:[DOCS](https://angular.io/api/common/http/HttpHeaders) – cyrix