Using the new http service in angular 2, I'd like do more with my errors than just throwing errors in the console. Unfortunately, I can't seem to access my object properties from within the catch callback function.
My http service call:
return this.http.get(this.apiUrl, options)
.map(this.extractData, this)
.catch(this.handleError)
My handleError callback fn:
handleError (error) {
console.log(this)//undefined!
if(error.status === 401){
this.router.navigate(['/login'])//because `this` is undefined, this does not work
}
...
}
According to rxjs docs, catch doesn't support a second thisArg
argument, which is very useful in the map function:
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()
}
So how can I call or use a property of my service from within the handleError
callback?
Your problem is that you reference a function directily so you lose its context (the this
) at execution.
To prevent from this, you need to wrap your method:
return this.http.get(this.apiUrl, options)
.map(this.extractData, this)
.catch(err => {
this.handleError(err);
})
or leverage the bind
method:
return this.http.get(this.apiUrl, options)
.map(this.extractData, this)
.catch(this.handleError.bind(this)
But there is drawbacks to use the second approach with TypeScript since you lose types.
See this link:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With