2016-12-07 55 views
3

我想檢查我的回覆是否包含正文內容。我會認爲res.totalBytes會這樣做,但它總是未定義的。如何檢查Angular2的http.response中的空響應主體?

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不確定的,即使身體上有個大大的對象?

+0

'console.log(typeof res);'print to your console? – echonax

+0

只需打印「對象」。如果我打印出'res.status',我得到'200',而不是'totalBytes',它的工作原理就像我期望的響應一樣。 – WillyC

+1

我不認爲'totalBytes'被實現。正文可以用'res.text()'獲得。是否有避免異常的真正原因? Promise/observable錯誤處理是處理預期故障的最直接方式。 – estus

回答

1

對於totalBytesbytesLoaded,它們不是標準屬性,有些時候它們將是未定義的。所以你不能用它們來檢查身體是否存在。

我的當前。解決方案是使用結果[「_體」],如:

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

雖然「_body」不在界面存在,但它在實際的響應存在。至少它在我的應用程序中起作用。