我正在尝试添加一个新的 AsyncValidator 来检查用户的电子邮件是否已存在于数据库中。 以下是可能的验证器:
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;
})
);
}
}
服务中的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);
});
}
它报告以下错误:
A function whose declared type is neither 'void' nor 'any' must return a value.
这个函数应该怎么修改?
最佳答案
您正在订阅
Observable,它将消耗包装在其中的值。
使用 map
而不是 subscribe
并从中返回一个 boolean
值::
isEmailExistEx(email: string): Observable<boolean> {
return this.http.post(this.baseUrl + "auth/verify", { email })
.pipe(
map((val: any) => val.result ? true : false)
);
}
关于javascript - 以 Angular 添加 AsyncValidator 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57264824/