(编辑器:VS Code; typescript :2.2.1)
目的是获取请求响应的headers
假设在服务中使用 HttpClient 发送 POST 请求
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", // to display the full response
responseType: "json"
};
return this.http.post(sessionUrl, body, options)
.subscribe(response => {
console.log(response);
return response;
}, err => {
throw err;
});
}
HttpClient Angular Documentation
第一个问题是我有一个 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() 方法的 ref 时,我指向这个原型(prototype)(我使用 VS 代码)
post(url: string, body: any | null, options: {
headers?: HttpHeaders;
observe?: 'body';
params?: HttpParams;
reportProgress?: boolean;
responseType: 'arraybuffer';
withCredentials?: boolean;
}): Observable<ArrayBuffer>;
但我想要这个重载方法:
post(url: string, body: any | null, options: {
headers?: HttpHeaders;
observe: 'response';
params?: HttpParams;
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<HttpResponse<Object>>;
所以,我尝试用这个结构修复这个错误:
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
我还得到了@Supamiu 解决方案不支持的媒体类型,所以它在我的标题中是一个错误。因此,上面的第二个解决方案(使用 Response 类型)也应该有效。但我个人认为将“Http”与“HttpClient”混合使用不是一个好方法,所以我会保留 Supamiu 的解决方案
最佳答案
您可以观察到完整的响应,而不仅仅是内容。为此,您必须将 observe: response 传递到函数调用的 options 参数中。
http
.get<MyJsonData>('/data.json', {observe: 'response'})
.subscribe(resp => {
// Here, resp is of type HttpResponse<MyJsonData>.
// You can inspect its headers:
console.log(resp.headers.get('X-Custom-Header'));
// And access the body directly, which is typed as MyJsonData as requested.
console.log(resp.body.someField);
});
关于javascript - Angular 4.3.3 HttpClient : How get value from the header of a response?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45505619/