Lab 04 : Validateur Asynchrone
📖 Ressources​
🚀 Code de Départ​
step-3-album-wholesale-v16-post-add-album-form-array
Continuez depuis le résultat du Lab 03. Si vous avez besoin de repartir à zéro, utilisez step-3-album-wholesale-v16-post-add-album-form-array comme base et complétez d'abord le Lab 03.
Dans ce lab, vous allez construire un validateur asynchrone qui vérifie si un album existe déjà en effectuant des requêtes HTTP. Vous allez utiliser des opérateurs RxJS comme debounceTime et switchMap pour optimiser la validation, et afficher des états de chargement pendant la validation asynchrone.
📝 Instructions​
Étape 1 : Créer un Validateur Asynchrone​
Créez un validateur asynchrone qui retourne un Observable.
L'
AlbumServiceexposeisArtistExist(name)etisAlbumExist(artist, name). Utilisez celui qui correspond Ă votre formulaire. Cet exemple valide le champ artiste :
import { AbstractControl, AsyncValidatorFn } from '@angular/forms';
import { of } from 'rxjs';
import { map, debounceTime, switchMap } from 'rxjs/operators';
import { AlbumService } from '../services/album.service';
export function artistExistsValidator(albumService: AlbumService): AsyncValidatorFn {
return (control: AbstractControl) => {
if (!control.value) return of(null);
return of(null).pipe(
debounceTime(300),
switchMap(() => albumService.isArtistExist(control.value)),
map(exists => exists ? { artistExists: true } : null)
);
};
}
Étape 2 : Appliquer au FormControl​
Ajoutez le validateur asynchrone comme troisième paramètre :
albumForm = this.fb.group({
artist: ['', [Validators.required], [artistExistsValidator(this.albumService)]]
});
Étape 3 : Afficher l'État Pending​
Affichez un indicateur de chargement :
<span *ngIf="albumForm.get('artist')?.pending">
Vérification...
</span>
<mat-error *ngIf="albumForm.get('artist')?.errors?.['artistExists']">
Cet artiste existe dĂ©jĂ
</mat-error>