angular - 如何将函数转换为 Angular8 中表单控件的异步验证器?
问题描述
我有一个日期类型的表单控件,允许用户选择一个日期。我想创建一个异步验证器来检查提交的日期是否在我的数据库中已经存在 x 次。如果是这样,请提供以下错误:
order.get('DateOfDelivery').errors?.exists
我在我的类商店组件中创建了这个函数(它对我的数据库起作用。它在查询日期返回适当数量的订单):
checkDeliveriesDate(event) {
console.log(event.target.value);
let date = { date: event.target.value };
this.SS.getOrdersPerDate(date).subscribe(
res => {
console.log(res);
/*
if (res.length>3){
formcontrol for e should turn invalid
}
else{
valid
}
*/
},
err => {
console.log(err);
}
)
}
这是表单控件。我知道异步验证器需要成为第三个参数-
DateOfDelivery: new FormControl('', Validators.required),/*AsyncValidatorHere*/),
这是HTML-
<input type="date" class="form-control" formControlName="DateOfDelivery" (change)='checkDeliveriesDate($event)'>
我很感激帮助。先感谢您
编辑:
checkDeliveriesDateValidator(ctrl: AbstractControl) {
if (!ctrl || String(ctrl.value).length === 0) {
console.log("!c|| String (c.value).length ===0")
return null;
}
return (ctrl && ctrl.value) ? this.SS.getOrdersPerDate({ date: ctrl.value }).pipe(
map(res => {
let deliveriesDate:any=res;
console.log(deliveriesDate);
if (deliveriesDate.length>3){
return {exists: true};
}
else{
return null;
}
})
) : null;
}
异步验证器正在产生此错误-
错误类型错误:无法读取未定义的属性“SS”
解决方案
you return the observable and use the map operator to transform the response into the validator return type, and also make it expect an abstract control as argument, like so:
checkDeliveriesDateValidator(ctrl: AbstractControl) {
// add in basic null checks
return (ctrl && ctrl.value) ? this.SS.getOrdersPerDate({ date: ctrl.value }).pipe(
map(res => {
console.log(res);
if (res.length>3){
//formcontrol for e should turn invalid
return {exists: true};
}
else{
return null;
}
})
) : null;
}
then use like:
DateOfDelivery: new FormControl('', Validators.required, checkDeliveriesDateValidator)
推荐阅读
- mongodb - LogStash:ElasticStash 的 MongoDB 输入插件
- android - Android Camera2 dumpsys 显示“Source Crop”中的变化我怎么知道是什么原因造成的?
- sql - 如何按行获取唯一值 - SQL Server
- json - 如果键匹配,则从 bash 中的 json 中提取特定键值
- javascript - 如何删除滚动事件监听器?
- mongodb - 缺少位置“位置”类型的以下属性:mongodb 中的祖先起源、哈希、主机、主机名等
- bi-publisher - 在 Oracle BIP 中创建日期参数时,是否有可能在 Date From Option 中传递“SYSDATE”?
- c# - 如何在 Swagger-ui 发出的 oauth2/token 调用中发送“观众”字段?
- java - log4j MDC Loader java1() 在 jdk11 上返回 true
- python - 如何将键中的嵌套python字典值替换为用点分隔的字符串格式?