在typescript中使用成功回调$ .get时,无法将数据绑定到类变量

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

 export class TestListViewModel { public personItems: KnockoutObservableArray; constructor() { this.personItems = ko.observableArray([]); this.person1 = new Person(); this.person1.name = ko.observable("Test 1"); this.person1.ssnId = ko.observable("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(data[index].name); this.person1.ssnId = ko.observable(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变量中。 为什么?

有人可以帮我解决我的代码有什么问题。 谢谢。

这是javascript的范围问题。

你能试试下面的代码吗?

 export class TestListViewModel { public personItems: KnockoutObservableArray; constructor() { const self = this; self.personItems = ko.observableArray([]); self.person1 = new Person(); self.person1.name = ko.observable("Test 1"); self.person1.ssnId = ko.observable("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(data[index].name); self.person1.ssnId = ko.observable(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 } 

这是该课程的完整代码吗? 是否在构造函数之外的任何位置访问了personItems ? 我猜想在调用$get之后,在返回之前还有其他操作personItems ,并将其大小设置为0。