1

I have a service that injects my AuthenticationService. In this service I initiate a third party typescript client and register a method inside the service as the exception handler.

My issue is that when the exception handler gets called the AuthenticationService has become undefined. I set breakpoint in constructor and can see the _auth variable is populated properly. But when exception handler gets called it is undefined. I tried setting it as a property but same behaviour occurs.

This is my service:

@Injectable({
  providedIn: 'root'
})
export class DomainAlertsService {
  client : JsonServiceClient;

  constructor( private _auth: AuthenticationService ) { 
    this.client = new JsonServiceClient(environment.apiUrl);
    this.client.exceptionFilter = this.exceptionHandler;
  }

  exceptionHandler(ex : Response)
  {
    if(ex.status == 401)
    {
        this._auth.logout(); // _auth is now undefined
        location.reload(true);
    }
    else{
      console.log("unhandled exception");
      console.log(ex);
    }

  }

  //.. other methods removed

}

I imagine this is some sort of scoping issue but I am not sure what is going on. Why is _auth undefined when exceptionHandler() method called?

Guerrilla
  • 13,375
  • 31
  • 109
  • 210
  • 1
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – ConnorsFan Nov 01 '18 at 21:04

1 Answers1

4

I think you need to bind it to the scope of the component, like so:

this.client.exceptionFilter = this.exceptionHandler.bind(this);
David Anthony Acosta
  • 4,766
  • 1
  • 19
  • 19