2017-07-20 26 views
4

在服務上,有這樣的代碼:角4:收到錯誤消息在訂閱

getUser(id){ 
    return this.http.get('http:..../' + id) 
     .map(res => res.json()); 
    } 

在組件:

this.myService.getUser(this.id).subscribe((customer) => { 
    console.log(customer); 
    this.customer = customer, 
    (err) => console.log(err) 
}); 

當它的「客戶」的存在,沒問題,我得到所有關於客戶的信息。

當id不存在時,web api返回帶有消息的'BadRequest'。我怎樣才能得到這個消息?狀態?

感謝,

回答

7

(err)需求是customer脂肪箭頭之外:

this.myService.getUser(this.id).subscribe((customer) => { 
    console.log(customer); 
    this.customer = customer, 
}, 
(err) => {console.log(err)}); 

爲了得到錯誤味精後面,添加一個catch將返回錯誤對象:

getUser(id){ 
    return this.http.get('http:..../' + id) 
    .map(res => res.json()) 
    .catch(this.handleError); 
} 

private handleError(error: any) { 
    let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error'; 
    return Observable.throw(error); 
} 
+0

並獲得消息? –

+0

需要一個'catch'。更新了答案:) – Nehal

+1

錯誤對象是否顯示在控制檯中?如果確實如此,那麼您可以簡單地在胖箭頭內部執行err._body以訪問該消息。 – Nehal

0

有時您在不使用箭頭功能的情況下致電catch時,如下所示

getUserList() { 
    return this.http.get(this.constURL + '/loans/all', this.headerOptions) 
    .catch(this.handleError); 
} 

handleError(error: Response) { 
    if (error.status == 500) {  
     this.router.navigate(['/login']); 
    } else { 
     return Observable.throw(error); 
    } 
} 

然後它給

錯誤類型錯誤的錯誤:無法讀取屬性「導航」的未定義沒有得到這個

由於功能的HandleError你accessible..if安慰this.router那麼這個對象不是你會得到不確定的.. 所以這個對象沒有工作,沒有得到路由器的所有可用的方法

所以,你必須在這裏使用箭頭功能類似下面

getUserList() { 
    return this.http.get(this.constURL + '/loans/all', this.headerOptions) 
    .catch(error => { 
     return this.handleError(error); 
    }); 
} 

handleError(error: Response) { 
    if (error.status == 500) {  
     this.router.navigate(['/login']); 
    } else { 
     return Observable.throw(error); 
    } 
} 

此外,如果你並沒有提及handlerError函數返回然後再重新拋出錯誤,如

參數類型的「(錯誤:任意)=>無效」是不能分配給類型的參數

所以它必須爲handlerError函數鍵入return。

入住詳情here。他已經解釋了很好的代碼以及所有可能的錯誤和解決方案。爲我工作