2017-03-12 27 views
2

我一直在玩弄角度2並嘗試實現處理錯誤。從響應對象中獲取特定值

現在我有我發佈到api的場景,並且我希望它輸出從api返回的消息,如果它的請求不正確(400)。

這是迄今爲止的代碼,不知道如何進入下一階段。

return this.http.post('http://localhost:8088/api/NextLevel', JSON.stringify(value), options) 
        .toPromise() 
        .then((res: Response) => res.json()) 
        .catch((error: any) => { this.handleError(error); }); 

private handleError(error: any) { 
if(error.status == '400') { 
// output to console the data contained for key Message 
} 
} 

這是JSON對象的實例被返回:

{Message: "The level is not recorded", ModelState: Object} 

基本上我想輸出到控制檯「的電平不記錄」的消息。

+0

請添加到您的問題'的console.log(JSON.stringify(錯誤));' – Habeeb

+0

不此代碼工作? –

+0

@RomanC yup does – Aeseir

回答

0

這取決於你的迴應MIME類型。

如果JSONü希望..

response.json().data.Message OR 

response.json().Message 

如果文本ü希望

response.text() 
+0

不幸的是,我已經嘗試過那些,沒有任何工作 – Aeseir

+0

response.json()。body.Message ??? – danday74

+0

燁也試過。奇怪的。 – Aeseir