Kri*_*s-I 19 typescript angular
在服务中,有这样的代码:
getUser(id){
return this.http.get('http:..../' + id)
.map(res => res.json());
}
Run Code Online (Sandbox Code Playgroud)
在组件中:
this.myService.getUser(this.id).subscribe((customer) => {
console.log(customer);
this.customer = customer,
(err) => console.log(err)
});
Run Code Online (Sandbox Code Playgroud)
当存在"客户"时,没有问题我得到有关客户的所有信息.
当id不存在时,web api会返回带有消息的"BadRequest".我该怎么收到这条消息?地位?
谢谢,
Neh*_*hal 36
(err)
需要在customer
胖箭之外:
this.myService.getUser(this.id).subscribe((customer) => {
console.log(customer);
this.customer = customer,
},
(err) => {console.log(err)});
Run Code Online (Sandbox Code Playgroud)
要获取错误消息,请添加一个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);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
46544 次 |
最近记录: |