【问题标题】:Angular 4 : get error message in subscribeAngular 4:在订阅中获取错误消息
【发布时间】:2017-07-20 21:16:13
【问题描述】:

在服务中,有这样的代码:

  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._body 即可获取消息

标签: angular typescript


【解决方案1】:

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

【讨论】:

  • 并得到消息?
  • 为此需要catch。更新了答案:)
  • 错误对象是否显示在控制台中?如果是这样,那么您只需在粗箭头内执行 err._body 即可访问消息。
【解决方案2】:

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

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

【讨论】:

  • error.status >> 返回HTTP状态码error.error.message >> 返回服务自定义消息
【解决方案3】:

有时当你调用 catch 而不使用如下箭头函数时

getUserList() {
    return this.http.get(this.constURL + '/loans/all', this.headerOptions)
    .catch(this.handleError);
}

handleError(error: Response) {
    if (error.status == 500) {      
      this.router.navigate(['/login']);
    } else {
      return Observable.throw(error);
    }
}

然后它给出了错误

ERROR TypeError: Cannot read property 'navigate' of undefined not getting this

因为在 handleError 函数中这个对象是不可访问的..如果你控制台 this.router 那么你会得到 undefined.. 所以这个对象不工作并且没有得到路由器所有可用的方法

所以你必须在这里使用箭头功能,如下所示

getUserList() {
    return this.http.get(this.constURL + '/loans/all', this.headerOptions)
    .catch(error => { 
      return this.handleError(error);
    });
}

handleError(error: Response) {
    if (error.status == 500) {      
      this.router.navigate(['/login']);
    } else {
      return Observable.throw(error);
    }
}

另外,如果你没有提到 handlerError 函数的返回,那么它会再次抛出错误,就像

'(error: any) => void' 类型的参数不能分配给类型参数

所以有必要为 handlerError 函数键入 return。

查看详情here。他很好地解释了所有可能的错误和解决方案的代码..为我工作

【讨论】:

    【解决方案4】:

    您可以在回调参数中添加err.json()

    
    this.myService.getUser(this.id).subscribe((customer) => {
      console.log(customer);
      this.customer = customer,
      (err) => {
        const error_response = err.json(); // response body
        console.log(error_response)
      }
    });
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-04
      • 2018-04-19
      • 2021-11-18
      相关资源
      最近更新 更多