首页 > 解决方案 > 在 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 变量。

请帮助我如何做到这一点。

标签: javascriptjquerytypescript

解决方案


我能够通过使用下面的代码来解决这个问题。

$.get("https://somerestapi/api/TestLists", 
             (data: any) => {
                 for (var index in data) {
                    this.personItems.push(data[index]);
                 }
});

推荐阅读