Anmol Anmol - 1 year ago 43
jQuery Question

How to set classes's property in callback in TypeScript?

Here is what I am trying to do:

class User {

name: string;

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

successCallback(response: any) { = string;

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

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

var user: User = new User();
evaluates to undefined

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

Answer Source

This is because the method is evaluated in windows context.

Wrap the xhr.then call:

xhr.then(response => {

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