Angular 4.3.3 HttpClient:如何从响应的头部获取值?

17 浏览
0 Comments

Angular 4.3.3 HttpClient:如何从响应的头部获取值?

编辑器: VS Code; TypeScript: 2.2.1

目的是获取请求的响应头

假设一个POST请求,使用HttpClient在一个服务中

import {

Injectable

} from "@angular/core";

import {

HttpClient,

HttpHeaders,

} from "@angular/common/http";

@Injectable()

export class MyHttpClientService {

const url = 'url';

const body = {

body: 'the body'

};

const headers = 'headers made with HttpHeaders';

const options = {

headers: headers,

observe: "response", //显示完整的响应

responseType: "json"

};

return this.http.post(sessionUrl, body, options)

.subscribe(response => {

console.log(response);

return response;

}, err => {

throw err;

});

}

HttpClient Angular文档

第一个问题是我有一个TypeScript错误:

'Argument of type '{

headers: HttpHeaders;

observe: string;

responseType: string;

}' is not assignable to parameter of type '{

headers?: HttpHeaders;

observe?: "body";

params?: HttpParams; reportProgress?: boolean;

respons...'.

Types of property 'observe' are incompatible.

Type 'string' is not assignable to type '"body"'.'

at: '51,49' source: 'ts'

事实上,当我去参考post()方法时,我指向了这个原型 (我使用VS code)

post(url: string, body: any | null, options: {

headers?: HttpHeaders;

observe?: 'body';

params?: HttpParams;

reportProgress?: boolean;

responseType: 'arraybuffer';

withCredentials?: boolean;

}): Observable;

但是我想要这个重载的方法:

post(url: string, body: any | null, options: {

headers?: HttpHeaders;

observe: 'response';

params?: HttpParams;

reportProgress?: boolean;

responseType?: 'json';

withCredentials?: boolean;

}): Observable>;

所以,我尝试用这个结构来修复这个错误:

const options = {

headers: headers,

"observe?": "response",

"responseType?": "json",

};

并且它编译通过了! 但是我只得到了请求体作为json格式。

此外,为什么我必须在一些字段的末尾加上?符号?正如我在TypeScript网站上看到的,这个符号只是告诉用户它是可选的?

我也尝试使用所有的字段,有和没有?标记的

编辑

我尝试了Angular 4 get headers from API response提出的解决方案。对于map解决方案:

this.http.post(url).map(resp => console.log(resp));

TypeScript编译器告诉我map不存在,因为它不是Observable的一部分

我还尝试了这个

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

this.http.post(url).post((resp: Response) => resp)

它编译通过,但我得到了一个不支持的媒体类型的响应。

这些解决方案对于“Http”应该是有效的,但对于“HttpClient”却不起作用。

第2次编辑

我也得到了一个不支持的媒体类型的响应,所以这可能是我的头部出现了错误。所以上面的第二个解决方案(带有Response类型)也应该有效。但是,个人而言,我认为将“Http”与“HttpClient”混合使用不是一个好办法,所以我将保留Supamiu的解决方案。

0