0

Here is what I am trying to do:

class User {

    name: string;

    userService: UserService; //service which fetches data from server

    successCallback(response: any) {
          this.name = string; 
    }

    setUser() {     
       var xhr: JQueryXHR = this.userService.fetchUser(); //Returns JQueryXHR object
       xhr.then(this.successCallback);
    }
}

Now, when I call setUser method on an instance of the User class:

var user: User = new User();
user.setUser(); 

this.name in successCallback evaluates to undefined

How can I get hold of the attribute of the class in callback function?

Anmol Gupta
  • 2,797
  • 9
  • 27
  • 43

1 Answers1

1

This is because the method is evaluated in windows context.

Wrap the xhr.then call:

xhr.then(response => {
    this.successCallback(response);
});

The => will make sure that this refers to the instance of this class.

martin
  • 93,354
  • 25
  • 191
  • 226