【问题标题】:Angular 5 httpClient both HttpHeaders and a Response object?Angular 5 httpClient 既有 HttpHeaders 又有 Response 对象?
【发布时间】:2018-05-08 20:49:51
【问题描述】:

我正在使用带有 httpClient 的 Angular 5。

此代码使用 HttpHeaders 发送帖子。太好了!

const httpOptions = {
   headers: new HttpHeaders({
     'Content-Type': 'application/json',
     'Authorization': 'my-auth-token'
   }),
};


return this.http.post<any>(serviceUrl + url, dto, httpOptions)
  .pipe(
    catchError(this.handleError)
  );

此代码返回响应对象。太好了!

  return this.http.post<any>(serviceUrl + url, fileForUpload, { observe: 'response' })
    .pipe(
      catchError(this.handleError)
    );

我怎样才能两者兼得?使用 HttpHeaders 发布并获取响应对象?谢谢

【问题讨论】:

  • .post 的第三个参数是一个对象,它可以包含多个东西...另外请注意,您应该比any 更具体对于泛型类型,否则编译器根本无法帮助您进行响应。

标签: angular httpclient


【解决方案1】:
const httpOptions = {
   headers: new HttpHeaders({
     'Content-Type': 'application/json',
     'Authorization': 'my-auth-token'
   }),
   observe: "response"
};

return this.http.post<any>(serviceUrl + url, fileForUpload, httpOptions)
.pipe(
  catchError(this.handleError)
);

【讨论】:

    【解决方案2】:

    这行得通:

    export interface IRequestOptions {
      body?: any;
      headers?: HttpHeaders | { [header: string]: string | Array<string> };
      observe?: any;
      params?: HttpParams | { [param: string]: string | Array<string> };
      reportProgress?: boolean;
      responseType?: "json";
      withCredentials?: boolean;
    }
    
    const options: IRequestOptions = {
      headers: new HttpHeaders({
      "Content-Type": "application/json",
      "Authorization": "my-auth-token"
    }),
    observe: "response"
    };
    

    【讨论】:

      猜你喜欢
      • 2018-07-09
      • 2020-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-25
      • 2018-05-28
      • 1970-01-01
      • 2016-02-16
      相关资源
      最近更新 更多