如何在自定义验证器中使用可注入服务

How to use an Injectable Service in a custom Validator

我有这个场景:-

我正在我的应用程序中创建一个自定义验证器,它使用服务获取数据

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;
}

但它抛出以下错误:-

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

我是否可以在该函数中使用 angular 服务??

替换此

let iss : IndianStatesAndCitiesService;

var iss = new IndianStatesAndCitiesService();

您还没有创建服务对象试试这个