【发布时间】:2018-07-17 01:41:54
【问题描述】:
我正在使用 TypeScript。我正在尝试在 ViewModel 中调用 rest API,如下所示。
export class TestListViewModel {
public personItems: KnockoutObservableArray<Person>;
constructor() {
this.personItems = ko.observableArray([]);
$.get("https://somerestapi/api/TestLists",
function (data: any) {
for (var index in data) {
this.personItems.push(data[index]);
}
});
} //end of constructor
} //end of class
在 this.personItems.push(data[index]) 行中,在“this”处,我收到编译错误,因为 'this' 隐含类型为 'any',因为它没有类型注释强>
在这里我想在回调函数中访问我的 Viewmodel 变量。
请帮助我如何做到这一点。
【问题讨论】:
-
试试这个:
function (data: any) { // your existing code...}.bind(this)。或者你可以使用箭头函数 -
如果我执行 $.get("somerestapi/api/TestLists", function (data: any) { for (var index in data) { this.personItems.push(data[ index]); } }.bind(this));
-
如果我这样做 $.get("deleteuserrestapi.azurewebsites.net/api/TestLists", data => { for (var index in data) { this.personItems.push(data[index]); } });我在“data =>”处收到错误,因为“参数‘数据’隐含地具有‘任何’类型”
标签: javascript jquery typescript