Angular 9 - 无法读取未定义的 属性

Angular 9 - Cannot read property of undefined

我是 运行 一个使用 Angular CLI 9.0.7 的应用程序。在此应用程序中,有一个表单的字段需要验证其控制数字。为此,我创建了一个自定义验证器。

当表单上的字段发生变化时,自定义验证器会被激活以检查一致性。

Custom Validator 组件需要调用另一个 class 中的一个方法,该方法由其他组件共享,当它要执行这一行时,我收到消息 Cannot read 属性 'isCpf' 未定义。

我复制了自定义验证器中调用的内容,并通过了,但这不正确,很糟糕。

如何正确调用方法 isCpf 并使用良好的实践?

这是我的自定义验证器

    static cpfValido(control: AbstractControl): any | null {
        const cpf: string = control.value;

        if (cpf === '') {
            return null;
        }
        else {
            if (this.isCpf(cpf)) {  // When isCpf is called throw Cannot read property 'isCpf' of undefined
                null;
            }
            else {
                return { 'cpfValido': false };

            }
        }
    }

并且在同一个文件中这是一个被调用的方法

    private static isCpf(pNumeroCpf: string): boolean {
        if (!pNumeroCpf) return false;

        let nro: string = this.preencherComCaracterEsquerda(this.removerFormatacao(pNumeroCpf), this.SIZE_CPF, '0');
        let j: number = 0;
        let peso: number = 2;
        let soma: number = 0;
        let dvc: number[] = [0, 0];
        let dvi: number[] = [0, 0];

        if (this.temCaracterRepetido(nro)) return false;

        for (j = 0; j < 2; j++) {
            peso = 2;

            soma = this.aplicarPeso(nro.substring(0, nro.length - 2 + j), peso, 11);

            dvc[j] = (soma % 11) < 2 ? 0 : 11 - (soma % 11);
        }

        dvi[0] = parseInt(nro.charAt(nro.length - 2), 10);
        dvi[1] = parseInt(nro.charAt(nro.length - 1), 10);

        return (dvi[0] === dvc[0] && dvi[1] === dvc[1]);
    }

静态成员由 class 名称后跟其名称引用。有关详细信息,请参阅 here

所以你的情况是

export class ValidatorClass {
  static cpfValido(control: AbstractControl): any | null {
      const cpf: string = control.value;

      if (cpf === '') {
          return null;
      }
      else {
          if (ValidatorClass.isCpf(cpf)) {  // <-- use class name instead of `this`
              null;
          }
          else {
              return { 'cpfValido': false };

          }
      }
  }
  .
  .
}

我假设您的 class 名字是 ValidatorClass。请将其替换为您的真实 class 姓名。

问题是您试图在 static class 中调用 this。你不能那样做。 static classes应该是纯的。

这是一个正在发生的事情的例子:

class Person {
  constructor(name) {
    this.name = name;
  }
  static getName() {
    return this.name;
  }
  getNameWorks() {
    return this.name;
  }
}

const person = new Person('Joe');
// Non static method
console.log(person.getNameWorks());
// Exception
console.log(person.getName());

您可以通过 ClassName.method() 访问静态方法,但请记住,您不能在 static classes

中使用 this

所以你可以这样做:

class Person {
  constructor() { }
  static sayHello(text) {
    alert(text);
  }
}

Person.sayHello('hello');

话虽这么说,看来您只需替换:

this.isCpf(cpf)

WhateverTheClassNameIs.isCpf(cpf)