gpt4 book ai didi

javascript - 从 Angular 中的自定义验证器访问服务

转载 作者:行者123 更新时间:2023-11-30 09:19:26 24 4
gpt4 key购买 nike

我正在尝试访问我的服务以检查验证器,但我得到的只是充满错误的控制台我确定我只是语法不佳=/

验证器:

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)

最佳答案

您必须将服务传递给验证器,这里没有依赖注入(inject),因为这不是 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

关于javascript - 从 Angular 中的自定义验证器访问服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52683527/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com