小编典典

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

javascript

(编辑:VS代码;打字稿:2.2.1)

目的是获取请求响应的标头

假设服务中具有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;
        });
}

第一个问题是我遇到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时,我指出了这个原型(我使用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网站上看​​到的那样,该符号应该只是告诉用户它是可选的?

我也尝试使用所有字段,不带和带?分数

编辑

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

Typescript编译器告诉您映射不存在,因为它不是Observable的一部分

我也试过了

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

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

它可以编译,但是得到了不受支持的媒体类型响应。这些解决方案应适用于“ Http”,但不适用于“ HttpClient”。

编辑2

@Supamiu解决方案也得到了不受支持的媒体类型,因此标题中将出现错误。因此,上面的第二个解决方案(具有Response类型)也应该起作用。但从个性上来说,我认为这不是将“Http”与“ HttpClient”混合使用的好方法,因此我将保留Supamiu的解决方案


阅读 608

收藏
2020-05-01

共1个答案

小编典典

您可以观察到完整的响应,而不仅仅是内容。为此,您必须传递observe: responseoptions函数调用的参数中。

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);
  });
2020-05-01