Aller au contenu

Lab 04 : Validateur Asynchrone

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.

Créez un validateur asynchrone qui retourne un Observable.

L’AlbumService expose isArtistExist(name) et isAlbumExist(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)
);
};
}

Ajoutez le validateur asynchrone comme troisième paramètre :

albumForm = this.fb.group({
artist: ['', [Validators.required], [artistExistsValidator(this.albumService)]]
});

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>