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

标签 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 总是未定义?

最佳答案

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

我目前的 .解决方案是使用 result['_body'],例如:

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

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

关于angular - 如何检查 Angular2 的 http.response 中的空响应主体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41024593/

相关文章:

angular - 如何将预加载器添加到每个http请求(angular2)?

angular - 是否有必要取消订阅由 Http 方法创建的可观察对象?

javascript - Angular 2 在发布请求中动态更改基本 url

angular - 同时在 chrome 和 IE11 中支持 Angular Element 的问题

Angular 2 & RxJs catch 函数回调绑定(bind)到 'this' 导致 http 请求一遍遍重复

angular - 在 Angular2 的英雄之旅中找不到模块 './in-memory-data-service'

angular - Ngrx 一次分派(dispatch)一个 Action 多次

javascript - Angular 5 - 如何在用户点击目标元素外部时触发事件

angular - 即使实际值相同,状态更改时组件也会重新渲染