0

I'm having an issue with AsyncValidators. Normally the promise being resolved is dependent upon code being called by the promise itself, but what about when the code is being called from outside and the promise has to listen for it? I'm not sure I'm explaining this correctly, but here's an example:

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 */
  });
}

I did try this approach:

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;
  });
}

But this does not change the form's status. The callDone() seems to be resolved, but it's still not working. What might I be doing wrong?

user2850751
  • 53
  • 1
  • 1
  • 9
  • You could use an [RxJS Subject](http://reactivex.io/rxjs/manual/overview.html#subject) to let the AsyncValidator communicate with external code. The validator would subscribe to the Subject and the external code would emit a next or complete event on the Subject when appropriate. But... this pattern seems very strange. Why can't you trigger the request from the AsyncValidator? – AngularChef Feb 02 '17 at 08:23
  • Thanks for your reply! The reason is that the request is a subscription to some external JS code. – user2850751 Feb 02 '17 at 15:58

0 Answers0