angularfunctionangular-servicesangular-validationangular-validator

How to use an Injectable Service in a custom Validator


I have this Scenario:-

I am creating a customvalidator in my app which uses a service to get Data

import { AbstractControl } from '@angular/forms';
import { IndianStatesAndCitiesService } from './indianstatesandcities.service';
export function SpecificState(control: AbstractControl) {
    let iss : IndianStatesAndCitiesService;
    let getiss : string[] = [];
    for(let i in iss.getStatesAndCities()){
        getiss.push(i);
    }
    if (control.value !== undefined && (getiss.includes(control.value))) {
        return { 'specificState': true };
    }
    return null;
}

But it is throwing following Error:-

ERROR TypeError: Cannot read property 'getStatesAndCities' of undefined
    at SpecificState (specificstate.validator.ts:6)

Is there anyway i could use the angular service inside that function??


Solution

  • replace this

    let iss : IndianStatesAndCitiesService;
    

    with

    var iss = new IndianStatesAndCitiesService();
    

    you haven't created an object of service try this