在承诺中访问'this'

Lia*_*m M 7 scoping typescript angular

在下面的typescript函数中,'this'不会解析为EmailValidator的实例.如何更正此功能,以便它解析为正确的EmailVaildator实例,以便我可以访问_registerServices?

class EmailValidator {

    constructor(private _registerServices: RegisterServices) { }

    isAvailable(c: AbstractControl): Promise<ValidationResult> {
        let q = new Promise((resolve, reject) => {
            this._registerServices.emailIsAvailable(antiForgeryToken(), c.value)
                .then(result => {
                    // Need to actually check the result.
                    resolve({ "emailtaken": true })
                },
                error => {
                    // Need to communicate the server error? Probably not.
                    resolve({ "servererror": true })
                });
        });

        return q;
    }
}
Run Code Online (Sandbox Code Playgroud)

Thi*_*ilo 8

你输了this,因为你在这里isAvailableEmail作为一个"原始"功能传递:

email: ['', Validators.required, this._emailValidator.isAvailableEmail]
Run Code Online (Sandbox Code Playgroud)

您可以通过将其绑定到this(使用胖箭头)来解决此问题:

email: ['', Validators.required,
  (control) => { this._emailValidator.isAvailableEmail(control) }
]
Run Code Online (Sandbox Code Playgroud)