使用Angular的新HttpClient,如何在订阅事件时获取所有标头?

Ceo*_*aki 7 angular

我使用Angular 4.3.2和新的HttpClient来下载作为流发送的文件,我需要获取标题(特别是Content-Disposition),但它们似乎没有出现在响应中,即使我可以在Chrome的开发工具中查看使用该请求正确发送的标头.

这是代码:

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) => {}
    );
}
Run Code Online (Sandbox Code Playgroud)

调用此代码后,Chrome会在dev工具的网络标签中报告以下响应标头:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http:// localhost:4200
Content-Disposition:attachment; 文件名= doc5619362.pdf; filename*= UTF-8''doc5619362.pdf
内容长度:88379
内容类型:application/pdf
日期:星期四,03八月2017 09:43:41 GMT
服务器:Kestrel
Vary:Origin
X-Powered-By:ASP.净

关于如何访问响应中存在的所有标题的任何想法?不仅仅是Content-Disposition不存在,除了Content-Type之外,所有其他标题都不存在.

谢谢!

UPDATE

这是一个工作的Plunker演示了这个问题:https://plnkr.co/edit/UXZuhWYKHrqZCZkUapgC?p = preview

Pab*_*ano 15

问题不是Angular,是CORS握手:如果服务器没有明确允许你的代码读取标题,浏览器会将它们隐藏起来.服务器必须在其响应中添加标题Access-Control-Expose-Headers:<header_name>,<header-name2>以便让您读取它们,但是目前它只允许执行请求并通过添加读取响应的主体Access-Control-Allow-Origin