Javascript 在angular中添加AsyncValidator时出错
我正在尝试添加一个新的AsyncValidator来检查数据库中是否已经存在用户的电子邮件。 以下是may validator:Javascript 在angular中添加AsyncValidator时出错,javascript,angular,Javascript,Angular,我正在尝试添加一个新的AsyncValidator来检查数据库中是否已经存在用户的电子邮件。 以下是may validator: export class UniqueEmailValidator implements AsyncValidator { constructor(private webService: WebWrapperService) {} validate(ctrl: AbstractControl): Promise < ValidationEr
export class UniqueEmailValidator implements AsyncValidator {
constructor(private webService: WebWrapperService) {}
validate(ctrl: AbstractControl): Promise < ValidationErrors | null > | Observable < ValidationErrors | null > {
return this.webService.isEmailExistEx(ctrl.value)
.pipe(
map(res => {
console.log("get response" + res);
if (res) {
return { 'uniqueEmail': true};
}
return null;
})
);
}
}
导出类UniqueEmailValidator实现AsyncValidator{
构造函数(私有webService:WebWrapperService){}
验证(ctrl:AbstractControl):承诺|可观察{
返回此.webService.isEmailExistEx(ctrl.value)
.烟斗(
映射(res=>{
log(“获取响应”+res);
如果(res){
返回{'uniqueEmail':true};
}
返回null;
})
);
}
}
服务中的函数isEmailExistEx将向服务器发送post请求
isEmailExistEx(email: string): Observable<boolean> {
this.http.post(this.baseUrl + "auth/verify",
{
"email": email
})
.subscribe(
(val: any) => {
if (!val.result) {
return of(false);
} else {
return of(true);
}
},
response => {
return of(false);
},
() => {
return of(false);
});
}
isEmailExistEx(电子邮件:字符串):可观察{
this.http.post(this.baseUrl+“auth/verify”,
{
“电子邮件”:电子邮件
})
.订阅(
(val:any)=>{
如果(!val.result){
归还(假);
}否则{
返回(真);
}
},
响应=>{
归还(假);
},
() => {
归还(假);
});
}
它报告以下错误:
声明类型既不是“void”也不是“any”的函数必须返回值
我应该如何修改此函数?您正在订阅可观察对象,它将消耗其中包含的值 使用
map
而不是subscribe
ing并从中返回布尔值:
isEmailExistEx(email: string): Observable<boolean> {
return this.http.post(this.baseUrl + "auth/verify", { email })
.pipe(
map((val: any) => val.result ? true : false)
);
}
isEmailExistEx(电子邮件:字符串):可观察{
返回this.http.post(this.baseUrl+“auth/verify”,{email})
.烟斗(
映射((val:any)=>val.result?真:假)
);
}