首页 文章

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

提问于
浏览
10

Angular文档说:

响应正文不会返回您可能需要的所有数据 . 有时,服务器返回特殊 Headers 或状态代码以指示某些条件,并且检查这些条件是必要的 . 要做到这一点,你可以告诉HttpClient你想要完整的响应,而不仅仅是带有observe选项的body:

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 ......' . property '观察'的类型是不相容的 . 类型'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) => ...

2 回答

  • 20

    你必须内联选项 . 请参阅2017年8月9日 alxhubgithub ticket #18586 .

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

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

    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 (无论当前名称是什么)运营商

相关问题