【问题标题】:In angular 2+, unable to capture data coming in the response of HttpClient在角度 2+ 中,无法捕获来自 HttpClient 响应的数据
【发布时间】:2023-03-21 09:00:02
【问题描述】:

我有一个 URL 可以点击,比如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 格式的错误。

响应格式如下:

想知道哪里出了问题?来自 API 的数据是否格式不正确?

【问题讨论】:

  • 您的网址中好像漏掉了“//”
  • 现在在 const url 中添加了 '//'。

标签: angular angular-httpclient angular4-httpclient


【解决方案1】:

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

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

this.http.get(url, headers );

【讨论】:

  • 这是请求标头的样子,无需设置标头以启用 json 格式。 GET 主机: 连接:keep-alive 接受:application/json,text/plain,/ 来源:localhost:4200 User-Agent:Mozilla /5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36 Referer: localhost:4200 Accept-Encoding: gzip, deflate
【解决方案2】:

如果您使用的是 HttpClient,请这样做:

在 http.get 方法的标头选项中添加 observe : 'response' 并订阅以获取响应和错误..

您的查询的解决方案:

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
  }

【讨论】:

    【解决方案3】:

    在服务中尝试以这种方式获得响应。

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

    【讨论】:

      猜你喜欢
      • 2020-01-19
      • 1970-01-01
      • 2018-09-05
      • 2018-01-13
      • 2013-11-12
      • 1970-01-01
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多