Validatior Async Angular 5 does not show me messages

1

Hi, I am new at angular I have version 5 and I am trying to do a validation to verify if a data is registered in the database, the details is that when the validation is executed, the error message is not interpreted. it is a problem of how the service returns the validation this is the code that I am used.

rutExistValidator(): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } => {
    return this.apiValiRut(control.value).subscribe(data => {
       this.datos = data;
       if (this.datos.process) {
         return { 'rutExist': { value: control.value } };
       }
    });
  }
}

and the error shows like this.

<div *ngIf="form.controls['rut'].errors.rutExist">
  * este rut ya existe
</div>

If someone can guide would be very helpful thanks.

    
asked by Manuel José Rodriguez 09.05.2018 в 03:04
source

1 answer

1

Since the validator is asynchronous, it can not return anything other than an Observable. As you have written it does not work, it should be something like:

rutExistValidator(): ValidatorFn {
  return (control: AbstractControl): Observable<[key: string]: any }> => 
    this.apiValiRut(control.value).map(data => {
       if (data.process) {
         return { 'rutExist': { value: control.value } };
       }
       return null;
    });
  }
}

And, when you assign it as a validator to the form , you have to do a .bind(this) so you can call your method apiValiRut . In addition, asynchronous validators are declared in a separate array of synchronous validators: formBuilder.group({ rut: ['',[<validadores>],[<validadores asincronos>]

    
answered by 11.05.2018 / 16:08
source