Javascript 如何使用(此)访问Angular 2 http rxjs catch函数中的对象属性

Javascript 如何使用(此)访问Angular 2 http rxjs catch函数中的对象属性,javascript,angular,rxjs,Javascript,Angular,Rxjs,使用angular 2中的新http服务,我想对我的错误做更多的处理,而不仅仅是在控制台中抛出错误。不幸的是,我似乎无法从catch回调函数中访问对象属性 我的http服务调用: return this.http.get(this.apiUrl, options) .map(this.extractData, this) .catch(this.handleError) 我的手机错误回拨fn: handleError (error) { co

使用angular 2中的新http服务,我想对我的错误做更多的处理,而不仅仅是在控制台中抛出错误。不幸的是,我似乎无法从catch回调函数中访问对象属性

我的http服务调用:

return this.http.get(this.apiUrl, options)
            .map(this.extractData, this)
            .catch(this.handleError)
我的手机错误回拨fn:

handleError (error) {
  console.log(this)//undefined!
  if(error.status === 401){
    this.router.navigate(['/login'])//because `this` is undefined, this does not work
  }
  ...
}
根据rxjs文档,catch不支持第二个
thisArg
参数,这在map函数中非常有用:

extractData(res) {
  console.log(this)//returns the instance of my service class, which is what I want
  this.someFunctionInMyService()//works great! In fact, I could call this.router.navigate if I wanted.
  return res.json()
}

因此,如何从
handleError
回调中调用或使用我的服务属性?

您的问题是,您直接引用了一个函数,因此在执行时丢失了它的上下文(“code>this)

要防止出现这种情况,您需要包装您的方法:

return this.http.get(this.apiUrl, options)
        .map(this.extractData, this)
        .catch(err => {
          this.handleError(err);
        })
或者利用
bind
方法:

return this.http.get(this.apiUrl, options)
        .map(this.extractData, this)
        .catch(this.handleError.bind(this)
但是,使用TypeScript的第二种方法有缺点,因为您会丢失类型

请参阅此链接:


太棒了!我对函数上下文缺乏理解。。。此外,我以前也尝试过用函数包装,但不是箭头函数,我忘记了箭头函数的真正用途。谢谢