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

问题描述 投票:0回答:2

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

当表单上的字段更改时,将激活“自定义验证器”以检查一致性。

Custom Validator组件,需要调用另一个类中的并且由其他组件共享的方法,并且在执行此行时,我收到消息Cannot read property'isCpf'of undefined 。

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

我该如何正确调用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]);
    }

angular customvalidator reactive-forms
2个回答
0
投票
因此,您的情况应该是

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 }; } } } . . }

我在这里假设您的班级名称是ValidatorClass。请用您的实际班级名称替换它。


0
投票
这里是正在发生的事的示例:

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());
© www.soinside.com 2019 - 2024. All rights reserved.