首页 > 解决方案 > Angular 5 - 如何使用 HTTPRespose.blob()?

问题描述

在 Angular 4 中,我曾经通过 angular 4 http 库进行 http get 或 post 调用,将任何 excel 或 pdf 文件下载为 blob。

我在 Angular 4 中的代码曾经看起来像这样:

import { Http, Response, Headers, RequestOptions,ResponseContentType   } from '@angular/http';
...................................

getExcelOrPDF(URL: string) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json' );        
    return this.http.get(URL, {headers: headers, responseType: ResponseContentType.Blob
  }).map(response => this.getData(response)) .catch(error => this.handleError(error));
}
    

    
    
public getData(res: Response) {
    console.log("getData()---Enter");
    let headers = res.headers;
    let contentType = headers.get('Content-Type');
    var blob;
    try {
        if(contentType === 'pdf' || contentType === 'application/pdf') {
            blob = new Blob([res.blob()], { type: "application/pdf"});
        } else {
            blob = new Blob([res.blob()], { type: "application/vnd.ms-excel"});
        }
    }
    catch (e) {
        console.debug(e);
    }
    console.log("getData()-Exit");
    return blob;
}

现在,我们都知道在 Angular 5 中,我们支持 HTTPClient 模块和 HTTPClient,我正试图摆脱 Angular 4 获取数据的方式。所以,我已经导入了 HTTPClient、HTTPResponse 等。

我在 Angular 5 中的代码如下所示:

import { HttpClient, HttpResponse , HttpHeaders} from '@angular/common/http';
...................................

getExcelOrPDF(URL: string) {
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json' );        
    return this.http.get(URL, {headers : headers, responseType: 'blob' as 'json'
 }).map(response => this.getData(response)) .catch(error => this.handleError(error));
}
    

    
    
public getData(res: HttpResponse<any>) {
    console.log("getData()---Enter");
    let headers = res.headers;
    let contentType = headers.get('Content-Type');
    var blob;
    try {
        if(contentType === 'pdf' || contentType === 'application/pdf') {
            blob = new Blob([res.blob()], { type: "application/pdf"});
        } else {
            blob = new Blob([res.blob()], { type: "application/vnd.ms-excel"});
        }
    }
    catch (e) {
        console.debug(e);
    }
    console.log("getData()-Exit");
    return blob;
}

但是,在 angular 4 代码完美运行的地方,上面的 angular 5 代码给了我几个错误:

有人可以让我知道我在这里做错了什么吗?任何帮助都深表感谢。

标签: excelangular5blobhttpclienthttpresponse

解决方案


我犯了一个愚蠢的错误,因此我面临很多问题。

首先:当我们使用 HTTPClient 而不是 HTTP 时,我们应该像这样创建标头:

let headers = new HttpHeaders();
headers  = headers.append('Content-Type', 'application/json' );

需要将 headers 对象分配回 headers ,否则实际的 headers 对象将为空。

其次:像这样进行http调用:this.http.get(URL, {headers : headers, observe: 'response', responseType: 'blob'}

第三: res.blob()在 HTTPResponse 中不可用。相反,我们应该使用:res.body

经过互联网上数百篇文档和文章以及无数次尝试和错误,我能够想出一个令人满意的解决方案。

希望这对遇到类似问题的其他人有所帮助。


推荐阅读