Javascript 类中的包验证方法(角度)

Javascript 类中的包验证方法(角度),javascript,angular,typescript,validation,Javascript,Angular,Typescript,Validation,嘿,我正在努力让我的应用程序代码看起来更好,更有条理。现在我在表单的组件中有一个验证。如何创建新类并在表单组中使用此验证方法 我将发布我的代码: export class AddMovieComponent implements OnInit { movieForm: FormGroup; constructor( private fb: FormBuilder, private dataService: DataService, ) { } ng

嘿,我正在努力让我的应用程序代码看起来更好,更有条理。现在我在表单的组件中有一个验证。如何创建新类并在表单组中使用此验证方法

我将发布我的代码:

export class AddMovieComponent implements OnInit {


  movieForm: FormGroup;

  constructor(
    private fb: FormBuilder,
    private dataService: DataService,
  ) {


  }

  ngOnInit() {


    this.movieForm = this.fb.group({
      title: ['', [Validators.required, this.titleValidator.bind(this)]],
     ...
  }

  titleValidator(control: AbstractControl) { --> I want this method in a CustomValidators class
    if (control && (control.value !== null || control.value !== undefined)) {
      for (let i = 0; i < this.dataService.getTitles().length; i++) {
        if (control.value == this.dataService.getTitles()[i]) {
          return {
            isError: true
          };
        }
      }
      return null;

    }
  }
导出类AddMovieComponent实现OnInit{
电影形式:FormGroup ;;
建造师(
私人fb:FormBuilder,
私有数据服务:数据服务,
) {
}
恩戈尼尼特(){
this.movieForm=this.fb.group({
标题:[''[validator.required,this.titleValidator.bind(this)],
...
}
titleValidator(control:AbstractControl){-->我希望在CustomValidators类中使用此方法
if(control&(control.value!==null | | control.value!==未定义)){
for(设i=0;i
我试图创建一个新类,只是添加了验证方法,但结果是整个语法都出了问题。我希望有人能在这里给我一些指导


非常感谢!

只需创建一个新服务并在服务中添加方法。然后在您想要使用该方法的位置注入服务,如下所示:

使用服务的组件:

constructor(private myService: MyService) {
  // you might need this next line in your case
  myService.titleValidator = myService.titleValidator.bind(this)
}

ngOnInit() {
  this.movieForm = this.fb.group({
    title: ['', [Validators.required, this.myService.titleValidator()]],
   ...
}
服务如下所示:

@Injectable({                  
  providedIn: 'root' // this line means you don't need to add it to a providers array and it will be loaded on demand and is accessible at the root level, it creates a single instance of the service that is accessible anywhere
})                             
export class MyService {                           
  constructor() { }           
  titleValidator(control: AbstractControl) {
    // blah blah
  }       
}                              

您也可以创建一个类并将其导出(导出类MyClass)在声明该类的文件中,并将其导入使用该类的组件中。但在Angular世界中,服务更为常见。

因此,如果我创建一个新类,我还需要将其添加到表单froup所在的组件中?如何?在类文件中导出类名称…在组件中导入它…从“/path”导入类名称