The AsyncValidator validates form fields before submission, which will be validated against an asynchronous source.
The AsyncValidator is an interface implemented by classes that perform asynchronous validation.
How to reproduce it
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { AbstractControl, AsyncValidator, ValidationErrors } from "@angular/forms";
import { Observable } from "rxjs";
@Injectable({
providedIn: 'root'
})
export class Demo implements AsyncValidator {
constructor(private http: HttpClient) {
}
validate(control: AbstractControl<any, any>): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
const { value } = control;
console.log(value)
console.log(this.http);
return new Promise((resolve, reject) => {
resolve({ "test": "done" });
});
}
registerOnValidatorChange?(fn: () => void): void {
throw new Error("Method not implemented.");
}
}
Error
ERROR - TypeError: Cannot read properties of undefined (reading 'http') at validate
Solution
Update the validate method to the property with the arrow function.
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { AbstractControl, AsyncValidator, ValidationErrors } from "@angular/forms";
import { Observable } from "rxjs";
@Injectable({
providedIn: 'root'
})
export class Demo implements AsyncValidator {
constructor(private http: HttpClient) {
}
validate = (control: AbstractControl<any, any>): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => {
const { value } = control;
console.log(value)
console.log(this.http);
return new Promise((resolve, reject) => {
resolve({ "test": "done" });
});
}
registerOnValidatorChange?(fn: () => void): void {
throw new Error("Method not implemented.");
}
}