javascript - 在 typescript 中调用 rest API 时面临错误,因为“'this' 隐式具有类型'any',因为它没有类型注释”
问题描述
我正在使用打字稿。我正在尝试在 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 变量。
请帮助我如何做到这一点。
解决方案
我能够通过使用下面的代码来解决这个问题。
$.get("https://somerestapi/api/TestLists",
(data: any) => {
for (var index in data) {
this.personItems.push(data[index]);
}
});
推荐阅读
- twitter-bootstrap - Bootstrap:一种模式未显示,但另一种模式显示
- javascript - 如何向 React 原生闪屏添加功能?
- azure-devops - 如何在 Azure Devops 中对发布管道进行路径筛选
- json - Json 数组问题.. 我真的需要帮助 --- .net core mvc
- android - Android gradle 模块循环依赖
- mongodb - 为同一查询生成不同的文档
- c# - “绑定”问题必须具有非空值
- ruby-on-rails - 如何验证取决于不同的提交按钮
- c# - Terminal.Gui c# - 有什么方法可以将 Dim 转换为 int?
- javascript - Typescript React 无法识别传递给功能组件的道具,ts 2740