如何在Angular中获取HttpClient模块的状态码

4

如何使用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 请求的状态码。

3
这个问题得到了解答吗?获取状态码http.get响应angular2 - Tobias S.
仍然如何打印状态码,例如200、201、205等。 - Santhosh
字面上,提到的帖子的第一个答案展示了如何打印状态码。 - Tobias S.
3个回答

4
使用来自 '@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个参数。 - Santhosh
第三个参数应该是一个具有头部属性的对象。我扩展了上面的逻辑。 - Khumo Mogorosi
1
http.post() 的第三个参数必须是 { headers, observe: 'response' }。 - Yochyo

3

您需要在选项参数中添加 observe: 'response'。这样做可以使您的订阅中获得整个响应。

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

    this.http.post<HttpResponse<any>>(
      'URL',
      {
        dataSentHere: 'data',
      },
      {
        headers: header1,
        observe: 'response',
      },
    ).subscribe(
      (data: HttpResponse<any>) => {
        if (data.status === 200 || data.status === 202) {
          console.log(`Got a successfull status code: ${data.status}`);
        }
        console.log(`This contains body: ${data.body}`);
      },
      (err: HttpErrorResponse) => {
        if (err.status === 403) {
          console.error('403 status code caught');
        }
      },
    );
  }

参考链接: https://angular.cn/guide/http#读取整个响应


0
如果您正在使用HttpClient,这里有一个示例:
this.http.post(myRequest, body, { headers : myHeaders, observe: 'response' }).subscribe(
  data => {
    console.warn(JSON.stringify(data, null, 2));
  },
  error => {
    console.error(error.errorMessege);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接