Shyju S.
Shyju S.

Reputation: 31

How to parse REST API failure message using httpclient in Ionic 3

The web service returns the below json as response with status code 403.

{

"status": "failure",

"message": "Unauthorized request or the token is invalid"

}

How to capture the status and message using httpClient in ionic 3.

This is my code:

apiHttpOptions = {
    headers : new HttpHeaders(),
    params: new HttpParams(),
    observe: 'response' as 'response',
  };

//Authenticate Function

  public authenticate(){

    let postData = new FormData();
    postData.append("username", this.username);
    postData.append("password", this.password); 

    this.authResponse = this.http
      .post(this.baseUrl + "authenticate", postData,      this.apiHttpOptions)


  return new Observable(observer =>{
    this.authResponse.subscribe((response) => {
      console.log("======Authentication======");
      let data = response.body;
      console.log(data);
      this.authToken = data["_token"];
      this.storage.set('token',this.authToken);
      observer.next(data);


    }, err => {
      console.log("======Auth Error =========");
      // console.log(err);
      observer.error(err);
    })
  }) 
  }

Upvotes: 1

Views: 135

Answers (1)

Suresh Kumar Ariya
Suresh Kumar Ariya

Reputation: 9764

You can use 'observe' : 'response' in the options property.

const request = {
   params: null,
   body: null,
   observe: 'response',
   headers: ...,
};

HTTP Call:

return this._http
      .request<modelresponse>(method, url, request);

Upvotes: 1

Related Questions