我正在使用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
变量中。为什么?
请问有人可以帮助我我的代码有什么问题吗?谢谢。
答案 0 :(得分:0)
这是该课程的全部代码吗? personItems
是否可以在构造函数之外的任何地方访问?我猜想在调用personItems
之后和返回之前,还有一些操作$get
并将其大小设置为0的事情。
答案 1 :(得分: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
}