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)
});

当它是“客户”存在时,没问题我可以获得有关客户的所有信息。

当 id 不存在时,web api 会返回带有消息的“BadRequest”。我怎样才能得到这个消息?状态?

谢谢,

原文由 Kris-I 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 477
2 个回答

(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);
}

原文由 Nehal 发布,翻译遵循 CC BY-SA 3.0 许可协议

我向我的朋友寻求帮助,他告诉我:在组件位置 err.error.message 如下所示>>

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

原文由 aniran mohammadpour 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进