使用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