Alfons Ingomar Alfons Ingomar - 1 month ago 11
TypeScript Question

Accessing class function inside a function in TypeScript

I am building in application in Angular 2 and am still having some trouble understanding the this scope of TypeScript.

I have TypeScript class called SharedService, when the function handleError receives a 401 status, I want it to call logout(). This is also a function in the class.

A read that, in order to use functions in combination with this I should use the arrow function definition as I did in my example below, somehow this still returns:


TypeError: this.logout is not a function(…)


Do you guys know what I am doing wrong?

export class SharedService {

logout = () => {
console.log('Logout.');
}

//This method catches any errors that might arise upon http requests
handleError(error: any) {
if (error.status === 401) {
this.logout(); <----------------------------- This returns the error
}
console.error(errMsg); // log to console instead
}
}


The error occurs when this.logout() is called!

Answer

Use .bind(this)

logout() {
  ...
  return this._http.delete(url, options)
        .map(res => res)
        .catch(this.handleError.bind(this));

or arrow functions

logout() {
  ...
  return this._http.delete(url, options)
        .map(res => res)
        .catch((err) => this.handleError(err));

The disadvantage in this case is that the parameters need to be repeated with => while this is not necessary with .bind(this). When the callback is defined inline () => is usually more convenient.

Comments