After studying the documentation, I implemented an Angular async validator class as shown below:
import { Injectable } from '@angular/core';
import {
AsyncValidator,
AbstractControl,
ValidationErrors,
} from '@angular/forms';
import { XService } from '../../pages/x/x.service';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
@Injectable()
export class UniqueXValidator implements AsyncValidator {
constructor(private xService: XService) {}
validate(ctrl: AbstractControl): Observable<ValidationErrors | null> {
return this.xService.checkExists(ctrl.value).pipe(
map(exists =>
exists ? { uniqueX: true } : null,
),
catchError(() => of(null)),
);
}
}
Next, when attempting to attach it programmatically to a form control, I used the following code:
this.form.controls['code'].setAsyncValidators(
UniqueXValidator,
);
A tooltip error message appeared in VS Code when hovering over "UniqueXValidator" in the previous code snippet. It stated:
Argument of type 'typeof UniqueXValidator' is not assignable to parameter of type 'AsyncValidatorFn | AsyncValidatorFn[]'.
Type 'typeof UniqueXValidator' is missing the following properties from type 'AsyncValidatorFn[]': pop, push, concat, join, and 25 more.ts(2345)
UPDATE: This issue may have been caused by a compatibility mismatch between my Angular version (7) and the version referenced in the documentation (11).