为什么我的构造函数参数私有 class 成员在 运行 时未定义?

Why is my constructor parameter private class member undefined at run-time?

我 运行 遇到一个问题,我的私有 class 变量在 运行 时未定义。密码是:

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 中的私有正则表达式变量在 运行 时未定义(我已确认正在传递正确的值) .我读过在 Angular2 中有一些需要考虑的依赖注入条件,但我什么都做不了。本质上,我已经尝试将 classes 列为 @Injectable,以及其他类似的东西。我得到的确切错误是:

EXCEPTION: TypeError: Cannot read property 'test' of undefined

谢谢

最终编辑

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

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本身的问题。事实上,在引用函数时,需要绑定到一个对象才能使用this关键字。

使用 bind 方法应该可以解决您的问题:

constructor(private fb:FormBuilder) {
  this.usernameValidation = new FormValidation(
              AdminRegistrationValidations.username);

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