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

Using the new http service in angular 2, I would like to do more with my errors than just throwing errors in the console. Unfortunately, I cannot access my object properties from the catch callback function.

My http service call:

return this.http.get(this.apiUrl, options) .map(this.extractData, this) .catch(this.handleError) 

My callback handleError 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 the docs, rxjs catch does not support the second argument to thisArg , 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 the property of my service from the handleError ?

+6
source share
1 answer

Your problem is that you are referencing a function, so that you lose its context ( this ) when executed.

To prevent this, you need to wrap your method:

 return this.http.get(this.apiUrl, options) .map(this.extractData, this) .catch(err => { this.handleError(err); }) 

or use the bind method:

 return this.http.get(this.apiUrl, options) .map(this.extractData, this) .catch(this.handleError.bind(this) 

But there are drawbacks to using the second approach with TypeScript, since you are losing types.

See this link:

+8
source

All Articles