0

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??

Dhiresh Budhiraja
  • 2,575
  • 5
  • 17
  • 26
  • Have you injected IndianStatesAndCitiesService this service in your constructor? – Sneha Pawar Jan 17 '19 at 06:13
  • 1
    Possible duplicate of [Inject custom service into a custom Validator](https://stackoverflow.com/questions/42646440/inject-custom-service-into-a-custom-validator) – TheParam Jan 17 '19 at 06:20

1 Answers1

2

replace this

let iss : IndianStatesAndCitiesService;

with

var iss = new IndianStatesAndCitiesService();

you haven't created an object of service try this

Sneha Pawar
  • 1,097
  • 6
  • 14