Angular 4/5 HttpClient : Argument of type string is not assignable to 'body'

标签 angular typescript angular-httpclient

Angular 文档说:

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

但是当我尝试这样做时,出现编译时错误(虽然没有运行时错误,但按预期工作):

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 ticket #18586 , alxhub 于 8 月 9 日发表 2017.

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 : Argument of type string is not assignable to 'body' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47761262/

相关文章:

angular - 如何修复: Property 'seedrandom' does not exist on type 'Math'

angular - 如何让 vsCode 了解自动补全的深度依赖导入?

typescript - 类型 'string | boolean' 不可分配给类型 'never' 。类型 'string' 不可分配给类型 'never'

angular - 在 Angular 8 中订阅 Observable 组件时遇到问题

angular - 如何在 Angular 中获取 HttpClient.Post 请求的响应头

angular - Angular 报告进度返回上传文件总数而不是进度

Angular CLI(v.1.0.1) 不允许用于开发目的的子域 : Invalid Host Headers

angular - 在Angular 6中通过http get处理复杂对象

typescript - webdriverio 5.7.5 出现错误 $(...).setValue 不是函数

typescript - 如何将推断的参数连接到用于调用 TypeScript 函数的类型