I am using TypeScript
. I am trying to bind the response from rest API to a variable in a ViewModel
like below:
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
Please see my comments in the code. When I am giving the data to personItems
variable in constructor then I can see the data in the variable. But when I am doing the same in success cal back of $.get
then data is not getting added to personItems
variable. Why?
Could some one please help me what is wrong with my code. Thanks.