0

i'm creating a HttpClient for my Angular2 typescript app and I'm stuck in error handler.

I want to emit an event when I catch a 401 error, and I'm able to catch the error but not to trigger my event, because the .catch needs to be attached to a function of type Observable, so I dont have access of my HttpClient Class this scope.

errorHandler (error:any) : Observable<any> {
  if(error.status == 401) {
    // I want to call this.myOtherMethod() here!
    this.events.publish('token_expired'); // Will throw this.events is undefined
    console.log(error);
  }

  return Observable.throw(error.json());
}

get(url) : Observable<any> {
  return this.http.get(url, {
    headers: this.customHeaders
  }).catch( this.errorHandler );
}

So I know I cant access my this.events from inside this function, but what's the workaround? How can I inject the events there?

gfviegas
  • 58
  • 4

1 Answers1

1

The problem is that you reference the errorHandler method so you lose the value of the this keyword. It's the way JavaScript works.

You could try the following to prevent from this:

get(url) : Observable<any> {
  return this.http.get(url, {
    headers: this.customHeaders
  }).catch( (error:any) => {
    return this.errorHandler(error);
  });
}

or

get(url) : Observable<any> {
  return this.http.get(url, {
    headers: this.customHeaders
  }).catch( this.errorHandler.bind(this) );
}

You need to be aware of the drawback when using the bind method with TypeScript:

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Perfectly answered! Worked like a charm. I was way too worried about the function type and I didn't noticed the scope killing reference. Thank You! Marked as solved. – gfviegas May 31 '16 at 19:03