typescript 怎样才能得到HttpClient模块的状态码的Angular

i86rm4rw  于 2023-02-17  发布在  TypeScript
关注(0)|答案(3)|浏览(145)

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

ltqd579y

ltqd579y1#

使用'@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))

}
axr492tv

axr492tv2#

如果您使用的是HttpClient,下面是一个示例:

this.http.post(myRequest, body, { headers : myHeaders, observe: 'response' }).subscribe(
  data => {
    console.warn(JSON.stringify(data, null, 2));
  },
  error => {
    console.error(error.errorMessege);
});
v2g6jxz6

v2g6jxz63#

您需要将observe: 'response'添加到options参数中,这样您就可以在订阅中获得整个响应。

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');
        }
      },
    );
  }

参考:www.example.comhttps://angular.io/guide/http#reading-the-full-response

相关问题