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?
This is because the method is evaluated in window
s 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.