从Angular中的Custom Validator访问服务

时间:2018-10-06 21:34:05

标签: javascript angular typescript validation

我正在尝试访问我的服务以检查验证程序,但我得到的只是控制台中充满了错误,我敢肯定我对语法问题= /

验证者:

import { DataService } from './services/data.service';
import { AbstractControl, FormGroup } from '@angular/forms';



export function titleValidator(control: AbstractControl,dataService:DataService) {

    console.log(dataService.moviesArray) -->> How can I access this service?
    if (control && (control.value !== null || control.value !== undefined)) {


        if (control.value=="test") {
            return {
                isError: true
            };
        }
    }

    return null;
}

组件:

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

如果任何人甚至还有其他解决方案可以在组件本身中进行自定义验证,那么我需要任何帮助..谢谢!

更新:错误:

AddMovieComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property 'moviesArray' of undefined
    at titleValidator (validator.ts:8)
    at forms.js:602
    at Array.map (<anonymous>)
    at _executeValidators (forms.js:602)
    at FormControl.validator (forms.js:567)
    at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl._runValidator (forms.js:2510)
    at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl.updateValueAndValidity (forms.js:2486)
    at new FormControl (forms.js:2794)
    at FormBuilder.push../node_modules/@angular/forms/fesm5/forms.js.FormBuilder.control (forms.js:5435)
    at FormBuilder.push../node_modules/@angular/forms/fesm5/forms.js.FormBuilder._createControl (forms.js:5473)

1 个答案:

答案 0 :(得分:2)

您必须将服务传递给验证器,这里没有依赖项注入,因为这不是Angular指令,而是纯函数。完成此操作的方法是使用一种接受服务并创建验证器功能的工厂方法。

export function titleValidator(dataService:DataService): ValidatorFn {
  return (control: AbstractControl) => {
    console.log(dataService.moviesArray) // now you can :)

    // Test for control.value only, for eg:
    if (control.value && dataService.moviesArray.includes(control.value))
      return null;
    else
      return { 'movieNotFound' : { value: control.value } };
  }
}

用法:

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

由于Angular仅使用有效控件调用验证器函数,因此无需检查控件是否存在。仅测试该值。更多信息here