PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 14, 2022

[FIXED] How to get the response of a post api call then show error on the page

 November 14, 2022     angular, api, error-handling, post, typescript     No comments   

Issue

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


Solution

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}`)
        }
      })
  }


Answered By - nate-kumar
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing