在角度2+中,无法捕获HttpClient响应中的数据

时间:2018-06-05 11:57:27

标签: angular angular-httpclient angular4-httpclient

我有一个要点击的网址,比如http://172.22.xx.xx:port/domain/section。我正在使用HttpClient进行http调用,并能够在开发人员工具的网络选项卡中查看200状态代码以及json数据。

组件 -

this.coreService.getData().subscribe(
      (data) => {
        console.clear();
        console.log('res: ', data);
      },
      (error) => {
        console.clear();
        console.log('err: ', error);
      }
    );

服务 -

getData() {
    const url = 'http://172.22.xx.xx:8080/domain/section';
    return this.http.get(url);
  }

问题是,我能够捕获的不是响应中的数据,而是 HttpErrorResponse 格式的错误。

enter image description here

响应采用以下格式:

enter image description here

想知道这出错的地方?来自API的数据是否格式不正确?

3 个答案:

答案 0 :(得分:0)

在服务中尝试以这种方式得到回应。

getData() {
    const url = 'http://172.22.xx.xx:8080/domain/section';
    return this.http.get(url).map(response => response.json()); 
}

答案 1 :(得分:0)

您需要设置标头以启用json格式

let headersConfig = {
   'Content-type': 'application/json; charset=utf-8',
   'Accept': 'application/json'
};
let headers = new Headers(headersConfig)

this.http.get(url, headers );

答案 2 :(得分:0)

如果您使用的是HttpClient,请执行以下操作:

在http.get方法的标题选项中添加观察:'响应',并订阅获取响应和错误..

您的查询解决方案:

<强> Component.ts

this.coreService.getData().subscribe(
      res => {
        console.clear();
        console.log("Response",res);
        //if you to get response in variable then do 
         this.responsedata = res.body;
      },
      err => {
        console.clear();
        console.log('err: ', err);
      }
    );

<强>服务

getData() {
    const url = 'http://172.22.xx.xx:8080/domain/section';
    return this.http.get(url,{observe: 'response'});
  }

全球处理错误

public errorHandler(err: HttpErrorResponse) : Observable<any>
  {
    if (err.error instanceof Error)
    {
      console.error("Client-side error occured.",err.status,err.error.message);
    }
    else 
    {
      console.error("Server-side error occured.",err.status,err.error.message);  
    }

    return ErrorObservable.throw(err || 'ERROR'); //throws error
  }