在打字稿中使用 $.get 的成功回调时无法将数据绑定到 class 变量

Not able bind the data to class variables while using success call back of $.get in typescript

我正在使用 TypeScript。我正在尝试将 rest API 的响应绑定到 ViewModel 中的变量,如下所示:

export class TestListViewModel {

  public personItems: KnockoutObservableArray<Person>;

  constructor() {
        this.personItems = ko.observableArray([]);

        this.person1 = new Person();
        this.person1.name = ko.observable<string>("Test 1");
        this.person1.ssnId = ko.observable<string>("1234");
        this.personItems.push(this.person1);

       //If i put a debugger here and see the "this.personItems()" in console 
       //I can see 1 object in personItems

        $.get("https://somerestapi/api/TestLists", 
             (data: any) => {
                 for (var index in data) {
                  this.person1 = new Person();
                  this.person1.name = ko.observable<string>(data[index].name);
                  this.person1.ssnId = ko.observable<string>(data[index].ssnId);
                  this.personItems.push(this.person1);
                  //If i put a debugger here and see the "this.personItems()" in console 
                 **//Now i am getting error "Uncaught TypeError: this.personItems is not a function"**
                 //If i do only "this.personItems" it is giving as "Undefined"
             } 
        });

  } //end of constructor

} //end of class

请看我在代码中的注释。当我在构造函数中将数据提供给 personItems 变量时,我可以看到变量中的数据。但是当我在 $.get 的成功回调中做同样的事情时,数据没有被添加到 personItems 变量中。为什么?

有人能帮我看看我的代码有什么问题吗?谢谢。

这是 class 的完整代码吗? personItems 是否在构造函数之外的任何地方访问?我猜想在调用 $get 之后和调用 returns 之前还有其他东西在操纵 personItems,并将其大小设置为 0。

这是 javascript 的作用域问题。

你能试试下面的代码吗?

export class TestListViewModel {

  public personItems: KnockoutObservableArray<Person>;

  constructor() {
    const self = this;
        self.personItems = ko.observableArray([]);

        self.person1 = new Person();
        self.person1.name = ko.observable<string>("Test 1");
        self.person1.ssnId = ko.observable<string>("1234");
        self.personItems.push(self.person1);

       //If i put a debugger here and see the "self.personItems()" in console 
       //I can see 1 object in personItems

        $.get("https://somerestapi/api/TestLists", 
             (data: any) => {
                 for (var index in data) {
                  self.person1 = new Person();
                  self.person1.name = ko.observable<string>(data[index].name);
                  self.person1.ssnId = ko.observable<string>(data[index].ssnId);
                  self.personItems.push(self.person1);
                  //If i put a debugger here and see the "self.personItems()" in console 
                 **//Now i am getting error "Uncaught TypeError: self.personItems is not a function"**
                 //If i do only "self.personItems" it is giving as "Undefined"
             } 
        });

  } //end of constructor

}