【问题标题】:Facing error as "'this' implicitly has type 'any' because it does not have a type annotation" while calling rest API in typescript在 typescript 中调用 rest API 时面临错误,因为“'this' 隐式具有类型'any',因为它没有类型注释”
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-06-16
    • 1970-01-01
    • 2021-09-27
    • 2020-03-06
    • 2019-08-04
    • 2018-10-29
    • 2020-09-25
    • 2022-10-08
    • 2017-12-09
    相关资源
    最近更新 更多