import { NovoUsuarioService } from './novo-usuario.service'; import { Injectable } from '@angular/core'; import { AbstractControl, AsyncValidator, ValidationErrors } from '@angular/forms'; import { first, map, switchMap, Observable } from 'rxjs';
@Injectable({ providedIn: 'root' }) export class UsuarioExisteService implements AsyncValidator {
constructor(private novoUsuarioService: NovoUsuarioService) { }
validate( control: AbstractControl ) : Observable<ValidationErrors | null> { return control.valueChanges.pipe( switchMap((username) => //prepara os dados da string digitada para o envio ao serviço this.novoUsuarioService.verificaSeUsuarioJaExiste(username) ), map((usuarioJaExiste) => //processa o resultado do serviço usuarioJaExiste ? { usuarioExistente: true } : null ), first() ); }
}
https://angular.io/guide/form-validation#reactive-component-class
this.novoUsuarioForm = this.formBuilder.group({ email: ['', [Validators.required, Validators.email]], fullName: ['', [Validators.required, Validators.minLength(4)]], userName: ['', [Validators.required, minusculoValidator], [this.usuarioExistenteService.validate.bind(this.usuarioExistenteService)]], password: ['', [Validators.required]] })