Custom AsyncValidator ERROR – TypeError: Cannot read properties of undefined (reading ‘http’) at validate 

Angular

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.");
    }
}
https://www.mldgroup.com

Vyštudovaný top manažér pôsobiaci najmä ako manažér, marketér, softvérový inžinier, konzultant, bloger, YouTuber a zatiaľ neúspešný hudobník a producent. V rámci praxe pôsobil v rôznych odvetviach na rôznych pozíciách v malých aj veľkých firmách, vrátane spoluprác a partnerstiev s významnými firmami či poradenskými spoločnosťami.

Pridaj komentár

Vaša e-mailová adresa nebude zverejnená. Vyžadované polia sú označené *