Angular 2 & RxJs catch 函数回调绑定到'this'导致http请求一遍遍重复

Angular 2 & RxJs catch function callback binding to 'this' causes http request to be repeated over and over

我有一个方法来处理来自 http 请求的错误,它看起来像这样

public handleError(err: any, caught: Observable<any>): Observable<any> {

  //irrelevant code removed
  this.logger.debug(err);//example of problem 
  return caught;
}

它是这样调用的(示例方法,但显示错误)

  public makeHttpCall() {
    this.http.get("http://api.exmaple.com/getsomedata")
      .map(r=> r.json())
      .catch(this.handleError);
  }

上面代码的问题在于,当在 handleError 方法中调用 this.logger.debug(err) 时,this 不再引用 class 进行 http 调用,但是引用 CatchSubscriber。

看这里:

所以我把.catch(this.handleError);改成了.catch(this.handlError.bind(this));

这有效,现在当我调用 this.logger.debugthis 指的是正确的对象。问题是,http 请求被一遍又一遍地调用, 看这里:

这只会在应用 .bind(this)

后发生

我不明白为什么会这样

*********编辑*********

.catch(handleError).catch((a,b)=>handleError(a,b)) 的更改修复了 this 的引用,但 http 请求只是一遍又一遍地发送垃圾邮件,但只有在请求失败时才会发生。如果请求成功,它只会发生一次。

当您使用 .catch(this.handleError); 传递函数时,它会失去其上下文 this。参见 Why do I lose the context of this in Javascript?

最简单的方法是将函数调用包装到闭包中来解决这个问题。

.catch((err, caught) => this.handleError(err, caught));