Search code examples
typescriptangularscoping

Access 'this' Inside Promise


In the typescript function below, 'this' doesn't resolve to the instance of EmailValidator. How can I correct this function so it resolves to the correct instance of EmailVaildator and in turn, so that I can access _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;
    }
}

Solution

  • You are losing this, because you are passing around the isAvailableEmail as a "raw" function here:

    email: ['', Validators.required, this._emailValidator.isAvailableEmail]
    

    You can fix this by binding it to this (using the fat arrow):

    email: ['', Validators.required,
      (control) => { this._emailValidator.isAvailableEmail(control) }
    ]