【问题标题】:Typescript: How to invoke class function from anonymous function打字稿:如何从匿名函数调用类函数
【发布时间】:2022-11-26 23:38:26
【问题描述】:

有一个服务定义如下:

export class MyService {
    doSomething(callbacks: { onSuccess: (data: Object) => any, onError: (err: any) => any }) {
        // This function does something
    }
}

它在组件中使用如下:

export class MyComponent implements OnInit {
    someFunction(): void { 
        this.myService.doSomething(
            {
                onSuccess(data: Object) {
                    onSuccessFunction(data) // Error here
                },
                onError(err: any) {
                }
            }
        )
    }
    
    onSuccessFunction(data: Object) {
    }
}

从上面可以看出,在MyComponent中定义的onSuccessFunction,在匿名函数onSuccess中被调用。但打字稿仍然给出如下错误:

Property 'initActiveOrders' does not exist on type '{ onSuccess: (data: Object) => any; onError: (err: HttpErrorResponse) => any; }'.ts(2339)

可能的原因是什么?

【问题讨论】:

  • 你只需要添加this.吗?
  • @pzaenger 查看编辑后的问题,

标签: angular typescript


【解决方案1】:

看起来你忘了在第 5 行的方法调用之前添加 this.

【讨论】:

  • 请参阅编辑后的问题。它正在寻找匿名函数内部的函数。
猜你喜欢
  • 2019-12-25
  • 1970-01-01
  • 2017-05-16
  • 2023-01-17
  • 1970-01-01
  • 1970-01-01
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多