我正在使用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