angular - 预期验证器返回 Promise 或 Observable 异步验证器 FormGroup 角度 7
问题描述
希望你是安全的。我正在使用 anuglar 7,我正在通过 aysnc 验证 api 调用验证模板名称是否存在于 db 中。我将异步验证器作为第三个参数传递,但是当我在输入字段上输入内容时出现错误。谁能帮帮我。我搜索了很多帖子,但没有一个能帮助我。谢谢
问题 --> 当我输入一些值时,我得到“错误错误:预期的验证器返回 Promise 或 Observable。”
#下面是我的 create-table.component.ts 文件代码:
ngOnInit() {
this.getProducts();
this.table = new FormGroup({
tableName: new FormControl ('',
Validators.required
,this.customTableNameValidator.bind(this)
),
});
}
这是异步功能
customTableNameValidator() {
return (control: AbstractControl) => {
return this.dataService.templateDuplicate(control.value).pipe(
map((res) => {
console.log("result : ", res["message"]);
return res["message"] ? { templateExist: true } : null;
})
);
};
}
这是服务api调用代码。这里“res['message']”将返回布尔值
templateDuplicate(tableName: string): Observable<any> {
return this.http
.post<any>(this.appBaseUrl + "validate-template-name/" + tableName, null)
.pipe(
map((res) => {
console.log("Res : ", res["message"]);
return res["message"];
})
);
}
下面是 Html 文件元素标签
<input class="form-control" formControlName="tableName" />
下面是 api 响应。我正在获取“消息”属性值并在上面的代码中返回它。
{
"statusMessage": null,
"filePath": null,
"message": true
}
解决方案
修改您的代码以查看它是否对您有帮助
customTableNameValidator() {
return (control: AbstractControl) => {
return this.dataService.templateDuplicate(control.value).pipe(
map((res:any) => {
console.log("result : ", res["message"]);
return res["message"] ? { templateExist: true } : null;
})
);
};
}
ngOnInit() {
this.table = new FormGroup({
tableName: new FormControl ('',
[ Validators.required, this.customTableNameValidator]
),
});
}
推荐阅读
- spark-streaming - 如何从 kafka 读取 Avro Schema 类型的事件并将它们存储在 Hive 表中
- c# - 如何在 C# 中创建类似 String Literal Union 类型的 TypeScript
- r - 按组为 R PCoA 图的个体着色
- windows - 如何配置 Postman 以便为 Windows 生成 curl 代码
- android - 这是应用程序的主要活动。但是这段代码以某种方式使我的应用程序崩溃。应该进行哪些更改才能使其正常工作
- c# - 异步方法同步运行c#
- arrays - 如何在数组中找到大于某个列值的第一个零列(或最后一个非零列)
- ruby-on-rails - 设计,创建一个属于公司的用户
- kdb - 函数返回 kdb/q 中的表
- html - 对齐 div 容器内 div 行底部的按钮