在服务中,有这段代码:
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' 和一条消息。我怎样才能得到这条消息?状态?
谢谢,
最佳答案
(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);
}
关于 Angular 4 : get error message in subscribe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45225339/