gpt4 book ai didi

typescript - 访问 'this' 内部 promise

转载 作者:太空狗 更新时间:2023-10-29 17:18:28 26 4
gpt4 key购买 nike

在下面的 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;
}
}

最佳答案

您正在丢失 this,因为您在这里将 isAvailableEmail 作为“原始”函数传递:

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

您可以通过将它绑定(bind)到 this 来解决这个问题(使用粗箭头):

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

关于typescript - 访问 'this' 内部 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37288327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com