打字稿 – 访问’this’Inside Promise

前端之家收集整理的这篇文章主要介绍了打字稿 – 访问’this’Inside Promise前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在下面的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;
    }
}

解决方法

你输了这个,因为你在这里传递isAvailableEmail作为“原始”函数

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

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

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

猜你在找的Angularjs相关文章