0

我遇到了 AsyncValidators 的问题。通常,要解决的承诺取决于承诺本身调用的代码,但是当从外部调用代码并且承诺必须监听它时呢?我不确定我是否正确解释了这一点,但这里有一个例子:

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() 似乎已解决,但仍然无法正常工作。我可能做错了什么?

4

0 回答 0