首页 > 解决方案 > 如何在 Ionic 3 中使用 httpclient 解析 REST API 失败消息

问题描述

Web 服务返回以下 json 作为响应,状态码为 403。

{

"status": "failure",

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

}

如何在 ionic 3 中使用 httpClient 捕获状态和消息。

这是我的代码:

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

//认证函数

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

标签: angularionic3angular-httpclient

解决方案


您可以在选项属性中使用 'observe' : 'response'。

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

HTTP 调用:

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

推荐阅读