Home > other >  How to get the response of a post api call then show error on the page
How to get the response of a post api call then show error on the page

Time:10-14

const tokenClean = sessionStorage.getItem('token')?.replace(/[:{}"]/g, '');
  const tokenFinal = tokenClean?.replace(/token/g, '');
  const headers = {
    'Authorization': `Bearer ${tokenFinal}`,
    'Body': '{}',
    
  };
  this.http.post(apiUrl   "token/vendor/request/getproductlist", headers, { headers })
  .subscribe((data: any) =>
{ this.listDropDown2 = data; }

This is my code for calling an api post request, How do i get the error then show it on the page? If there is one

CodePudding user response:

As Angular's HttpClient makes use of the RxJs observable handlers, watching for an error in any HTTP call is the same as watching for an error in any other observable, e.g. by providing a second callback function as an argument to subscribe() (docs).

Note: The answer demonstrates this by providing an 'observer' object as an argument to subscribe() which contains the success (next) and error (error) handlers as keys on this object

This returns a HttpErrorResponse class (docs) which contains all of the metadata about the error:

  postProductList() {
    const tokenClean = sessionStorage.getItem('token')?.replace(/[:{}"]/g, '');
    const tokenFinal = tokenClean?.replace(/token/g, '');
    const headers = {
      'Authorization': `Bearer ${tokenFinal}`,
      'Body': '{}',
    };

    this.http.post(
      apiUrl   "token/vendor/request/getproductlist",
      headers,
      { headers }
    )
      .subscribe({
        next: (data: any) => {
          // any API success handling logic goes here (e.g. for http codes 2xx and 3xx)
          this.listDropDown2 = data;
        },
        error: (httpError: HttpErrorResponse) => {
          // any API error handling logic goes here (e.g. for http codes 4xx and 5xx)
          const errorValue: any | null = httpError.error;
          const errorCode: number = httpError.status;
          console.error(`Endpoint returned error ${errorValue} with status code ${errorCode}`)
        }
      })
  }
  • Related