我遇到了AsyncValidators的问题。通常,解决的承诺取决于promise本身调用的代码,但是从外部调用代码并且promise必须监听它时呢?我不确定我是否正确解释了这一点,但这是一个例子:
public valid: boolean;
ngOnInit() {
...
formControl = new FormControl('', this.asyncValidator.bind(this))
}
/* some code runs an external request and runs setValid() */
setValid(valid: boolean) {
this.valid = valid;
...
}
asyncValidator(): { [key: string]: any } {
...
return new Promise(resolve => {
/* somehow waiting on the setValid() function to be run */
});
}
我确实尝试过这种方法:
public valid: boolean;
ngOnInit() {
...
formControl = new FormControl('', this.asyncValidator.bind(this))
}
/* some code runs an external request and runs setValid() */
setValid(valid: boolean) {
if (this.callDone) {
if (valid) {
this.callDone(null);
}
else {
this.callDone({ 'wrong': true });
}
}
this.callDone = null;
this.valid = valid;
}
asyncValidator(): { [key: string]: any } {
if (this.callDone)
this.callDone(this.valid);
return new Promise(resolve => {
this.callDone = resolve;
});
}
但这不会改变形式的状态。 callDone()似乎已经解决,但它仍然无法正常工作。我可能做错了什么?