【问题标题】:How can get the status code of the HttpClient module in angular如何以角度获取 HttpClient 模块的状态码
【发布时间】:2021-12-22 04:24:03
【问题描述】:

如何使用HttpClient获取所有请求的状态码

apiCall() {
    let header1 = new HttpHeaders();
    header1 = header1.append('Content-Type', 'application/json');
    header1 = header1.append('Authorization', `Bearer ${this.token}`);

    this.http.post("URL",
      {
        "dataSentHere": "data"
      }, {
      headers: header1
    }).subscribe(data => {

      console.log(data);

    },
      (err: HttpErrorResponse) => {
        if (err.status === 403) {
         console.log("403 status code caught");
        }
      }

      
    )
  }

如何获取返回202、200等的http请求的状态码

【问题讨论】:

标签: angular typescript http angular-httpclient


【解决方案1】:

使用来自'@angular/common/http'HttpErrorResponseHttpResponse

apiCall() {
  let headers = new HttpHeaders();
  headers = headers.set('Content-Type', 'application/json');
  headers = headers.set('Authorization', `Bearer ${this.token}`);

  this.http.post<HttpResponse<any>>('URL', { data }, { headers }).subscribe(response => {
      console.log(response.status) // log status code
  }, (e: HttpErrorResponse) => console.log(e.status))

}

【讨论】:

  • 如何添加标题??我不能添加超过 3 个参数
  • 第三个参数应该是一个以标题为属性的对象。我扩展了上面的逻辑。
猜你喜欢
  • 2019-07-22
  • 2021-01-28
  • 2011-02-05
  • 1970-01-01
  • 2023-01-29
  • 2019-02-10
  • 1970-01-01
  • 2018-06-30
  • 2021-08-08
相关资源
最近更新 更多