Angular 4/5 HttpClient:字符串类型的参数无法分配给"body" [英] Angular 4/5 HttpClient: Argument of type string is not assignable to 'body'

查看:82
本文介绍了Angular 4/5 HttpClient:字符串类型的参数无法分配给"body"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angular文档说:

The Angular docs say:

响应主体不会返回您可能需要的所有数据.有时 服务器返回特殊的标头或状态代码以指示某些 条件,并进行检查.为此,您可以 告诉HttpClient您想要完整的响应,而不仅仅是正文 带有观察选项:

The response body doesn't return all the data you may need. Sometimes servers return special headers or status codes to indicate certain conditions, and inspecting those can be necessary. To do this, you can tell HttpClient you want the full response instead of just the body with the observe option:

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

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

But when I try that, I get a compilation time error (no runtime errors though, works as expected):

错误TS2345:类型为'{headers的参数:HttpHeaders;观察:字符串; }'不可分配给类型'{headers ?: HttpHeaders | {[header:string]:字符串|细绳[]; };观察?参数?:Ht ...'. 属性观察"的类型不兼容. 不能将类型"string"分配给类型" body"".

error TS2345: Argument of type '{ headers: HttpHeaders; observe: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'. Types of property 'observe' are incompatible. Type 'string' is not assignable to type '"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) => ...

推荐答案

您必须内联选项.参见 github票证#18586 ,由alxhub于8月9日输入 2017.

You have to inline the options. See github ticket #18586, entry by alxhub on August 9 2017.

Typescript需要能够静态地推断观察值和responseType值,以便为get()选择正确的返回类型.如果传入的类型错误的选项对象,则无法推断正确的返回类型.

Typescript needs to be able to infer the observe and responseType values statically, in order to choose the correct return type for get(). If you pass in an improperly typed options object, it can't infer the right return type.

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) => ...

这篇关于Angular 4/5 HttpClient:字符串类型的参数无法分配给"body"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆