角度2和RxJ的catch函数回调绑定到'this'导致HTTP请求一遍又一遍地重复 [英] Angular 2 & RxJs catch function callback binding to 'this' causes http request to be repeated over and over

查看:43
本文介绍了角度2和RxJ的catch函数回调绑定到'this'导致HTTP请求一遍又一遍地重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a method for handle our errors from http requests and it looks like this

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

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

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

It is invoked like this (example method, but shows the error)

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

上述代码的问题在于,在 handleError 方法 this 中调用 this.logger.debug(err)时,不再引用到从其进行http调用的类,但引用了CatchSubscriber.

The problem with the above code is that when calling this.logger.debug(err) in the handleError method this no longer refers to the class the http call was made from but references the CatchSubscriber.

请参阅此处:

所以我将 .catch(this.handleError); 更改为 .catch(this.handlError.bind(this));

这有效,现在当我调用 this.logger.debug this 引用正确的对象时.问题是,一遍又一遍地调用http请求,看到这里:

This works, now when i call this.logger.debug this refers to the correct object. The problem is, the http request gets called over and over and over, see here:

这仅在应用 .bind(this)

我不知道为什么会这样

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

*********EDIT*********

.catch(handleError)更改为 .catch((a,b)=> handleError(a,b))修复了的引用这,但是http请求只会一遍又一遍地发送垃圾邮件,但仅限于请求失败时.如果请求成功,则只会发生一次.

Change from .catch(handleError) to .catch((a,b)=>handleError(a,b)) fixes the reference of this but the http request just gets spammed over and over, but only when the request fails. If the request succeeds it only happens once.

推荐答案

当您使用 .catch(this.handleError); 传递函数时,它会丢失上下文 this .请参见为什么在Javascript中会丢失此上下文?

When you pass a function with .catch(this.handleError); it loses its context this. See Why do I lose the context of this in Javascript?

最容易地,您可以通过将函数调用包装到闭包中来解决此问题.

Most easily you can fix this by wrapping the function call into a closure.

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

这篇关于角度2和RxJ的catch函数回调绑定到'this'导致HTTP请求一遍又一遍地重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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