Angular http客户端:使用承载令牌和responseType = blob设置标头

时间:2018-04-19 15:41:16

标签: angular angular-httpclient

如何设置http客户端POST请求的标头,以便同时发送承载令牌和响应类型blob?

我目前的代码是:

public saveBook(format: string, req: Book) {

    var mediaType = 'application/pdf';

    this.http.post(this.ApiUrl + '/PDFBook', req, { responseType: "blob" }).subscribe(
        (response) => {
            var blob = new Blob([response], { type: mediaType });
            saveAs(blob, 'Book.' + format.toLowerCase());
        });
}

我需要附加当前标题这个持票人:

let headers = new HttpHeaders().set('Authorization', 'Bearer ' + localStorage.getItem('session_token'));

我该怎么做?

编辑:

我试过这样做:

let headers = new HttpHeaders().set('responseType', 'blob')
            .set('Authorization', 'Bearer ' + localStorage.getItem('session_token'));

但我得到一个解析错误,因为它无法找到'responseType'

3 个答案:

答案 0 :(得分:3)

您需要首先导入ResponseContentType:

import { ResponseContentType } from "@angular/http";

然后像在示例中一样创建标题对象:

let headers = new HttpHeaders().set('Authorization', 'Bearer ' + localStorage.getItem('session_token'));

之后,您可以将两个标题和Blob将作为响应类型的指示放在代码中,如下所示:

public saveBook(format: string, req: Book) {

var mediaType = 'application/pdf';

this.http.post(this.ApiUrl + '/PDFBook', req, {headers: this.headers, responseType: ResponseContentType.Blob}).subscribe(
    (response) => {
        var blob = new Blob([response], { type: mediaType });
        saveAs(blob, 'Book.' + format.toLowerCase());
    });
}

我不确定您是否还需要将Blob的内容类型指定为标题,在这种情况下您必须将它们添加到标题var(pe:application / pdf)中:

    this.headers.set('Accept','application/pdf');
    this.headers.set('Content-Type','application/pdf');

答案 1 :(得分:1)

试试这个:

options = new RequestOptions();
options.headers = new Headers();
options.headers.append('Authorization', bearerToken);
options.headers.append('responseType', 'blob')

this.http.post(this.ApiUrl + '/PDFBook', req, options)

对于HttpClient:

Haven自己做过这件事,你可以试试像:

{headers: this.headers, responseType: ResponseContentType.Blob as 'blob'}

即使这不起作用,请尝试:

{headers: this.headers, responseType: 'blob' as 'json'}

看起来很奇怪,看到this discussion

答案 2 :(得分:1)

我做到了。我只需要首先为令牌设置标头,然后像{ headers, responseType:'blob' }

那样连接它们

结果实际上就是这样:

public saveBook(format: string, req: Book) {
     let headers = new HttpHeaders().set('Authorization', 'Bearer ' + localStorage.getItem('session_token'));
    var mediaType = 'application/pdf';

    this.http.post(this.ApiUrl + '/PDFBook', req, { headers, responseType:'blob' }).subscribe(
        (response) => {
            var blob = new Blob([response], { type: mediaType });
            saveAs(blob, 'Book.' + format.toLowerCase());
        });
}