Angular 4:获取订阅中的错误消息 [英] Angular 4 : get error message in subscribe

查看:108
本文介绍了Angular 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)
});

当它是客户"存在时,我可以毫无问题地获得有关该客户的所有信息.

When it's the 'customer' exist, no problem I get all the information about the customer.

当ID不存在时,网络api会返回"BadRequest"并显示一条消息.我如何获得此消息?状态?

When the id does not exist, the web api return 'BadRequest' with a message. How can I get this message ? the status ?

谢谢

推荐答案

(err)必须位于customer粗箭头之外:

(err) needs to be outside the customer fat arrow:

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

要获取错误消息,请添加catch,它将返回错误对象:

To get the error msg back, add a catch that will return the error object:

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:获取订阅中的错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆