2017-07-20 24 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。他已经解释了很好的代码以及所有可能的错误和解决方案。为我工作