Angular 4/5 HttpClient:类型字符串的参数不能赋予'body'

时间:2017-12-11 20:55:42

标签: angular angular-httpclient

Angular文档说:

  

响应正文不会返回您可能需要的所有数据。有时   服务器返回特殊标头或状态代码以指示确定   条件,并检查那些是必要的。要做到这一点,你可以   告诉HttpClient您需要完整的响应,而不仅仅是正文   使用观察选项:

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);
  });

但是当我尝试这个时,我得到一个编译时间错误(尽管没有运行时错误,按预期工作):

  

错误TS2345:类型'{headers:HttpHeaders;观察:字符串; ''不能赋值给'{headers?:HttpHeaders |'类型的参数{[header:string]:string |串[]; };观察?:“身体”; params?:Ht ......'。     财产'观察'的类型是不相容的。       类型'string'不能分配给''body''。

为什么呢?我使用"@angular/http": "^5.1.0"

这是我的代码版本:

  login(credentials: Credentials): Observable<any> {
    const options = {
      headers: new HttpHeaders({'Content-Type': 'application/json'}),
      observe: 'response'
    };
    return this.httpClient.post<any>(`${environment.USER_SERVICE_BASE_URL}`,
      {'username': credentials.username, 'password': credentials.password}, options)
      .map((res) => ...

4 个答案:

答案 0 :(得分:28)

您必须内联选项。请参阅github ticket #18586alxhub 8月9日的报名  2017。

  

Typescript需要能够静态地推断observe和responseType值,以便为get()选择正确的返回类型。如果传入一个输入不正确的选项对象,则无法推断出正确的返回类型。

login(credentials: Credentials): Observable<any> {
    return this.httpClient.post<any>(`${environment.USER_SERVICE_BASE_URL}`,
      {'username': credentials.username, 'password': credentials.password}, {
      headers: new HttpHeaders({'Content-Type': 'application/json'}),
      observe: 'response'
    })
      .map((res) => ...

答案 1 :(得分:8)

我解决这个问题的方法是,没有内联选项(这可能导致代码不那么干净)就是为请求选项创建一个接口。代码如下所示:

export interface IRequestOptions {
    body?: any;
    headers?: HttpHeaders | { [header: string]: string | Array<string> };
    observe?: any;
    params?: HttpParams | { [param: string]: string | Array<string> };
    reportProgress?: boolean;
    responseType?: "arraybuffer" | "blob" | "json" | "text";
    withCredentials?: boolean;
}

然后将其用作:

const options: IRequestOptions = {
    headers: new HttpHeaders({"Content-Type": "application/json"}),
    observe: "response"
};
return this.httpClient.post(`${environment.USER_SERVICE_BASE_URL}`,
    {"username": credentials.username, "password": credentials.password}, options)
    .pipe(
        map((res: HttpResponse<any>) => ...
    );

原始帖子的更改使用lettablepipeable(无论当前的名称是什么)运营商

答案 2 :(得分:7)

打字稿抱怨这个问题

  

“字符串”类型不能分配给“正文”类型

要解决此问题,请手动将字符串转换为主体。示例:

    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      }),
      observe: 'response' as 'body'
    };
    return this.http.post<any>(url, data, httpOptions);

答案 3 :(得分:0)

import { HttpHeaders, HttpParams } from '@angular/common/http';
export interface IRequestOptions {
    headers?: HttpHeaders | { [header: string]: string | string[]; };
    observe: "response"; 
    params?: HttpParams | { [param: string]: string | string[]; };
    reportProgress?: boolean; 
    responseType?: "json";
    withCredentials?: boolean; 
}