如何检查Angular2的http.response中的空响应主体?

时间:2016-12-07 18:20:13

标签: angular angular2-http

我想检查一下我的回复是否包含正文中的内容。我原本以为res.totalBytes会这样做,但它总是未定义的。

this.http.get(this.url, this.options)
    .toPromise()
    .then( (res) => {
        console.log("totalBytes: "+res.totalBytes);//outputs 'totalBytes: undefined'
        console.log("res body: "+JSON.stringify(res.json()));//outputs a great big JSON object just as I would expect.
        });

检查身体是否为空(理想情况下不依赖于抛出异常)的最佳方法是什么?为什么即使身体中有一个很大的物体,totalBytes总是未定义?

2 个答案:

答案 0 :(得分:1)

对于totalBytesbytesLoaded,它们不是标准属性,有时它们将是未定义的。所以你不能用它们检查身体是否存在。

我的当前。解决方案是使用结果['_ body'],如:

if (res['_body']) {
  json = res.json()
}

虽然界面中不存在'_body',但它存在于实际响应中。至少它适用于我的应用程序。

答案 1 :(得分:0)

基于我的 Observable 的解决方案:(目前两者都是 Angular 11)

(对于两种解决方案,请确保将 { observe: 'response' } 作为 this.options 之一)

this.http.get(this.url, this.options)
.subscribe( (res) => {
  console.log(res.body['length']);
  if (res.body['length'] === 0) {
    console.log("Empty body!");
  }
} );

或基于 Promise 的解决方案:

this.http.get(this.url, this.options)
.toPromise()
.then( (res) => {
  console.log(res.body['length']);
  if (res.body['length'] === 0) {
    console.log("Empty body!");
  }
} );

然后在布尔值中使用它: res.body['length'] === 0

使用开发工具检查对象字段时的图像:https://imgur.com/YDRwUlB(当我尝试上传或使用图像上传器时出现“我是茶壶”错误,因此我必须这样做)-您可以看到它在 res.body 下包含一个 'length' 属性。

之前也尝试过使用 toPromise() 并在 .json 中进行转换,但了解到它不再受支持并且 Observables return .json() directly after Angular 4

我知道这是一个老问题,但自从我今天了解到这一点后,我想上传我的基于 Observable 和 Promise 的解决方案。希望这对未来的任何人都有帮助!

相关问题