You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 2 Http服务错误处理:Toastr无法在错误处理方法中生效

解决Angular中错误处理方法里无法调用Toastr服务的问题

我一眼就看出问题出在哪了——你在catch里直接传递this.handleError的时候,方法里的this上下文丢失了,不再指向你的DataService实例,所以this.toastr是undefined,自然弹不出提示。而成功回调里能正常用,是因为你在map的回调里直接写的代码,保留了当前实例的this指向。

给你两种简单的修复方案:

方案一:用箭头函数包裹handleError调用

在每个catch的地方,用箭头函数来调用handleError,这样会自动保留外层的this上下文:

getAll(url: string) {
  return this.http.get(environment.apiEndPoint+url,this.options)
    .map(response => response.json())
    .catch((error) => this.handleError(error)); // 箭头函数保留this
}

create(url: string,resource) {
  return this.http.post(environment.apiEndPoint+url, JSON.stringify(resource),this.options)
    .map(response => { 
      this.toastr.success('Data Saved Successfully');
      return response.json(); 
    })
    .catch((error) => this.handleError(error)); // 同样改这里
}

方案二:提前绑定this到handleError

在构造函数里把handleError的this绑定到当前实例,这样之后直接传递方法引用也不会丢上下文:

constructor( private http: Http , private toastr: ToastrService ) {
  let headers = new Headers();
  headers.append('Content-Type', 'application/json');
  headers.append('Authorization', 'Bearer '+localStorage.getItem('token'));
  this.options = new RequestOptions({ headers: headers });
  
  // 新增这行,绑定this到handleError
  this.handleError = this.handleError.bind(this);
}

// 之后getAll和create里的catch就不用改了,保持原来的写法
getAll(url: string) {
  return this.http.get(environment.apiEndPoint+url,this.options)
    .map(response => response.json())
    .catch(this.handleError);
}

你也可以直接把handleError定义成箭头函数,这样默认就会捕获当前类的this:

// 把方法改成箭头函数形式
private handleError = (error: Response) => {
  if (error.status === 403){
    this.toastr.error( 'User Login Failed');
    return Observable.throw(new BadInput(error.json()));
  }
  // ... 其他错误处理逻辑
}

选其中一种方法改完后,再测试错误场景,Toastr应该就能正常弹出错误提示了。

内容的提问来源于stack exchange,提问作者Jerin Jose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:02:33