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

Phi*_*hil 15 angular angular-httpclient

Angular文档说:

响应正文不会返回您可能需要的所有数据.有时,服务器返回特殊标题或状态代码以指示某些条件,并且检查这些条件是必要的.要做到这一点,你可以告诉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);
  });
Run Code Online (Sandbox Code Playgroud)

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

错误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) => ...
Run Code Online (Sandbox Code Playgroud)

Igo*_*gor 33

你必须内联选项.见GitHub的票#18586,进入由alxhub8月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) => ...
Run Code Online (Sandbox Code Playgroud)


Imt*_*que 20

打字稿抱怨这个问题

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

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

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

  • 也适用于“响应”。const options = {headers:headers,observe:response as'response'}; (2认同)

blo*_*p3r 9

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

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;
}
Run Code Online (Sandbox Code Playgroud)

然后这样使用:

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>) => ...
    );
Run Code Online (Sandbox Code Playgroud)

更改原始帖子使用lettablepipeable(今天的当前名称)运营商