Angular 如何将自定义验证器与服务一起使用
我尝试使用自定义验证器检查电子邮件是否已被接收。 根据文档和一些文章,我提出了以下代码: 在我的auth.service.ts中Angular 如何将自定义验证器与服务一起使用,angular,typescript,validation,Angular,Typescript,Validation,我尝试使用自定义验证器检查电子邮件是否已被接收。 根据文档和一些文章,我提出了以下代码: 在我的auth.service.ts中 checkEmail(email) { const r$ = of(true); const x$ = of(false); return this.http.post<any>(`${config.apiUrl}/users/email`, email) .pipe( mergeMap(v =>
checkEmail(email) {
const r$ = of(true);
const x$ = of(false);
return this.http.post<any>(`${config.apiUrl}/users/email`, email)
.pipe(
mergeMap(v =>
iif(
() => v,
r$,
x$
)
)
);
}
但它不起作用,如何使checkEmail()函数为验证器返回正确的数据您需要以下MOD:
ngOnInit() {
this.registerForm = this.formBuilder.group({
email: ['', [
Validators.required,
Validators.email
], [this.checkEmail.bind(this)]] // async validators go separate after sync validators
});
}
checkEmail(control: AbstractControl) {
if (control.value) {
return this.authService.checkEmail({email: control.value}).pipe(
map(response => {
return response ? { forbiddenName: {value: control.value}} : null;
}) // use observables, don't convert to promises
);
}
return of(null); // gotta return an observable for async
}
不需要,但也可以更简单/更干净:
checkEmail(email) {
return this.http.post<any>(`${config.apiUrl}/users/email`, email)
.pipe(
map(v => !!v) // map and coerce to bool
);
}
检查电子邮件(电子邮件){
返回此.http.post(`${config.apirl}/users/email`,email)
.烟斗(
映射(v=>!!v)//映射并强制到bool
);
}
您需要以下MOD:
ngOnInit() {
this.registerForm = this.formBuilder.group({
email: ['', [
Validators.required,
Validators.email
], [this.checkEmail.bind(this)]] // async validators go separate after sync validators
});
}
checkEmail(control: AbstractControl) {
if (control.value) {
return this.authService.checkEmail({email: control.value}).pipe(
map(response => {
return response ? { forbiddenName: {value: control.value}} : null;
}) // use observables, don't convert to promises
);
}
return of(null); // gotta return an observable for async
}
不需要,但也可以更简单/更干净:
checkEmail(email) {
return this.http.post<any>(`${config.apiUrl}/users/email`, email)
.pipe(
map(v => !!v) // map and coerce to bool
);
}
检查电子邮件(电子邮件){
返回此.http.post(`${config.apirl}/users/email`,email)
.烟斗(
映射(v=>!!v)//映射并强制到bool
);
}
首先,据我所知,这应该是一个异步验证器:异步验证器标记为,在同步验证器之后。首先,据我所知,这应该是一个异步验证器:异步验证器标记为,在同步验证器之后。