当前位置: 首页 > 知识库问答 >
问题:

Angular 4/5 HttpClient:string类型的参数不能分配给“body”

黎浩然
2023-03-14

棱角分明的医生说:

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

为什么?我使用“@angull/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) => ...

共有1个答案

娄利
2023-03-14

您必须内联选项。参见github门票#18586,2017年8月9日由alxhub进入。

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

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) => ...
 类似资料: