【发布时间】:2019-08-17 17:58:05
【问题描述】:
我有一个注册表单,我在表单控件上使用valueChanges 侦听器,并调用 http 服务,如果该值已经存在,则该服务会发布到服务器,例如电子邮件和用户名。如果服务器上已经存在该值,则返回状态码 403。我通过向用户显示消息来捕获并处理此错误,但我的问题是valueChanges 侦听器停止侦听,因此如果我只是更改表单值,则此代码是空闲的。即使在错误发生后,我可以让听众继续吗?我应该以另一种方式处理吗?谢谢。
这是监听器代码:
this.watchEmailSub = this.registerForm.controls.email.valueChanges.pipe(
debounceTime(500),
distinctUntilChanged(),
switchMap(v =>
this.regService.checkRegistrationValueExists('Email', v, this.registerForm.controls.email.valid)
)
).subscribe(returnValue => {
this.registerEmailError = null;
console.log('returnValue.message = ', returnValue.message);
},
(error) => {
console.warn('Error = ', error);
this.registerEmailError = 'This email already exists';
}
);
HTTP 服务代码:
checkRegistrationValueExists(type: string, value: string, formControlValid: boolean): Observable<any> {
// Code removed here that defines checkValueExistsUrl & checkValueExistsBody
if (formControlValid) {
return this.http.post<string>(checkValueExistsUrl, checkValueExistsBody);
}
return of({ message: `${type} invalid` });
}
【问题讨论】:
-
观察者的行为方式。一旦他们遇到错误,他们就会停止倾听。
标签: angular rxjs angular-reactive-forms