【问题标题】:TypeError: 'x' is not a function even when the method is definedTypeError:即使定义了方法,“x”也不是函数
【发布时间】:2021-10-23 16:59:25
【问题描述】:

我正在对一个文件运行一些测试,我收到这个奇怪的错误为 TypeError: this.activatedService.isVariableActivated is not a function 即使定义了函数。

这是我在 typescript 文件 activation.ts 中的代码 sn-p -

import { ActivationService } from 'activationService'
constructor(
   private activatedService: ActivationService)
onActivationVariable(testvar: string) {
{
  this.activatedService.isVariableActivated('ACTIVATION').then(
    isActivated => {
      console.log('value of isActivated:', isActivated);
      if (isActivated) {
           /*some functionality*/
      });

这是我在另一个服务打字稿文件activationService.ts中的一个类中的函数定义

export declare class ActivationService {
isVariableActivated(variableName: string, customTarget?: string): Promise<Boolean>;
}

当我从 onActivationVariable 函数调用 isVariableActivated 函数时,我收到此错误 -

TypeError: this.activatedService.isVariableActivated is not a function

我是 Angular/javascript 的新手。有人可以帮我解决这个问题吗?提前致谢。

【问题讨论】:

  • ActivationService 类中使用static 之前的isVariableActivated 方法
  • ActivationService的实例没有这个函数,可以看一下它的代码吗?

标签: javascript angular typescript typeerror


【解决方案1】:

如果你在构造函数中的activedService应该是ActivationService类本身,你必须用关键字static来定义它,这样它就变成了类的方法。

       export declare class ActivationService {
       static isVariableActivated(variableName: string, customTarget?: 
       string): 
       Promise<Boolean>;
       }

如果 activedService 是 ActivationService 的一个实例,则需要使用 new 关键字:

constructor(
private activatedService: new ActivationService())
onActivationVariable(testvar: string) {
{ ....

【讨论】:

  • 我试图包含静态,但它似乎不起作用.. :(
猜你喜欢
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 1970-01-01
  • 2020-03-25
相关资源
最近更新 更多