Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 737
Joao Avatar asked May 13 '16 14:05

Joao


1 Answers

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:

  • https://basarat.gitbooks.io/typescript/content/docs/tips/bind.html
like image 200
Thierry Templier Avatar answered Oct 26 '22 00:10

Thierry Templier