this is my code:
ngOnInit() {
this.form = new FormGroup({
name: new FormControl('', Validators.required),
lat: new FormControl('', Validators.required),
lon: new FormControl('', Validators.required),
countryId: new FormControl('', Validators.required)
}, null, this.isDupeCity());
this.loadData();
}
<!-- extra code -->
isDupeCity(): AsyncValidatorFn {
return (control: AbstractControl): Observable<{ [key: string]: any } | null> => {
var city = <City>{};
city.id = (this.id) ? this.id : 0;
city.name = this.form.controls['name'].value;
city.lat = +this.form.controls['lat'].value;
city.lon = +this.form.controls['lon'].value;
city.countryId = +this.form.controls['countryId'].value;
var url = environment.baseUrl + 'api/Cities/IsDupeCity';
return this.http.post<boolean>(url, city).pipe(map(result => {
return (result ? { isDupeCity: true } : null);
}));
}
}
The problem is that the async validator gets called on every keystroke. I'm following a book on Angular & C# and this is the book's github code. The author says "...we can reasonably expect the isDupeCity validator to be called once or twice for each form submission, which is perfectly fine in terms of performance impact. Everything is fine, then. Let's move on"