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

How to access object properties in Angular 2 http rxjs catch function with (this)

本文关键字:函数 catch rxjs 属性 对象 http 何使用 this Angular 访问      更新时间:2023-09-26

使用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-docs的说法,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回调中调用或使用我的服务的属性呢?

您的问题是直接引用函数,因此在执行时会丢失其上下文(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中使用第二种方法也有缺点,因为您会丢失类型。

请参阅此链接:

  • https://basarat.gitbooks.io/typescript/content/docs/tips/bind.html