【问题标题】:Angular HTTP request get response bodyAngular HTTP 请求获取响应正文
【发布时间】:2018-08-22 12:47:39
【问题描述】:

我目前正在尝试弄清楚如何获取响应正文。我可以在浏览器的网络控制台中将其视为字符串数组(这是我想要得到的),但使用我的代码只会返回一个对象:

this.http.request(req).subscribe(event => {
            if (event.type === HttpEventType.UploadProgress) {
                const percentDone = Math.round(100 * event.loaded / event.total);
                console.log(`File is ${percentDone}% uploaded.`);
            } else if (event instanceof HttpResponse) {
                console.log('File is completely uploaded!');
                console.log('resp: ' + event.body);
            }
          });

这是一个 POST 请求。

这是日志:

resp: [object Object]

【问题讨论】:

  • 当你打印事件时(没有 .body)你会得到什么?

标签: angular http request response


【解决方案1】:

你需要使用 JSON.stringify 来查看实际内容

 console.log('resp: ' + JSON.stringify(event.body));

如果您想从响应中访问特定字段,请使用 JSON.parse 转换为 Object

let filename = (JSON.parse(event.body)).fileName;

【讨论】:

  • 非常感谢!救了我很多次。祝你有美好的一天,兄弟
  • 无法这么快地标记它。我会。您是否也碰巧知道如何从中获取某个响应参数?像“文件名”?
  • 你必须使用 JSON.parse(event.body)
  • 然后使用点运算符访问
猜你喜欢
  • 2020-11-06
  • 1970-01-01
  • 1970-01-01
  • 2015-07-10
  • 1970-01-01
  • 2020-11-07
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
相关资源
最近更新 更多