javascript - 为什么我的构造函数参数私有(private)类成员在运行时未定义?

标签 javascript dependency-injection typescript undefined angular

我遇到了一个问题,我的私有(private)类变量在运行时未定义。代码是:

export class AdminRegistrationComponent {

    adminRegistrationForm:ControlGroup;
    usernameValidation:FormValidation;

    constructor(private fb:FormBuilder) {

        this.usernameValidation = new FormValidation(AdminRegistrationValidations.username);

        this.adminRegistrationForm = fb.group({
            username: new Control("", this.usernameValidation.valid)
        });
    }

    submit() {
        console.log(this.adminRegistrationForm);
    }
}

FormValidation:

export class FormValidation {

    constructor(private regex:RegExp) {
    }

    valid(control:Control):ValidationResult {

        if (this.regex.test(control.value)) {
            return null;
        }

        return {"valid”": true};
    }

    get():string {
        return this.regex.toString().slice(1, -1);
    }
}

问题是当在 this.usernameValidation 上调用 valid 时,FormValidation 中的私有(private)正则表达式变量在运行时未定义(我已确认正在传递正确的值)。我读过在 Angular2 中有一些需要考虑的依赖注入(inject)条件,但我什么都做不了。本质上,我已经尝试将这些类列为 @Injectable,以及其他类似的东西。我得到的确切错误是:

异常:TypeError:无法读取未定义的属性“test”

谢谢

最终编辑

下面提到的答案是我的有效函数需要是箭头函数:

valid = (control:Control):ValidationResult => {

    if (this.regex.test(control.value)) {
        return null;
    }

    return {"valid”": true};
}

最佳答案

he private regex variable in FormValidation is undefined at run-time (I have confirmed the right value is being passed in).

很可能 regex 未定义:

constructor(private regex:RegExp) {
}

如果不是,则调用 valid(control:Control):ValidationResult { 时使用了错误的 this。修复使用箭头:

valid = (control:Control):ValidationResult => {

    if (this.regex.test(control.value)) {
        return null;
    }

    return {"valid”": true};
}

关于箭头函数的更多信息:https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

视频 on this in TypeScript

关于javascript - 为什么我的构造函数参数私有(private)类成员在运行时未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35764257/

相关文章:

javascript - 用户在 Javascript 中输入后如何存储总分?

javascript - 使用正则表达式匹配学术列表中的名称和出版物标题

javascript - 如何根据第二个数组中的值从JS数组中删除对象

c# - Container 未在构造函数中设置属性

php - Symfony2 服务容器 - 将普通参数传递给服务构造函数

javascript - 在 socket.io 中使用箭头函数

javascript - 在 VS 中,有没有办法忽略某些 typescript 文件上的错误但仍将它们编译进去?

javascript - 分析通过路径列表的函数

java - 在 hibernate 中使用 "IN"运算符

javascript - 使用find typescript方法返回 Angular 4中的值