Angular 4:在订阅中获取错误消息
发布时间:2020-12-17 07:33:03 所属栏目:安全 来源:网络整理
导读:在服务中,有这样的代码: 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(
在服务中,有这样的代码:
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”.我该怎么收到这条消息?地位? 谢谢,
(错误)需要在客户胖箭之外:
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); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |