【发布时间】:2019-03-15 02:32:26
【问题描述】:
我有一个有效的异步验证器,它向服务器发出 HTTP 请求以检查用户名是否已被使用。 由于我不想在每次击键后调用 API,我需要对输入流进行去抖动。
我第一次在服务中有throttleTime,但是关于 SO 的另一个主题说这必须是订阅的人,但还没有运气!
我的组件:
this.form = this._fb.group(
{
username: ['', [Validators.required, Validators.maxLength(50), NoWhitespaceValidator], [IsUserIdFreeValidator.createValidator(this._managementService)]]
});
我的验证者:
export class IsUserIdFreeValidator {
static createValidator(_managementService: ManagementService) {
return (control: AbstractControl) => {
return _managementService.isUserIdFree(control.value)
.pipe(
throttleTime(5000),
(map(
(result: boolean) => result === false ? { isUserIdFree: true } : null))
);
};
}
}
我的服务:
public isUserIdFree(userId: string): Observable<{} | boolean | HttpError> {
const updateUserCheck: UpdateUserCheck = new UpdateUserCheck();
updateUserCheck.userID = userId;
return this._httpClient.post<boolean>('UserManagementUser/IsUserIdFree', updateUserCheck));
}
【问题讨论】:
-
我认为你需要去抖动,而不是节流
-
阅读这篇博文,这正是你要找的blog.thoughtram.io/angular/2016/01/06/…
-
@ritaj 我试过了,我也试过使用延迟
-
那是因为你不是在 HTTP 调用上去抖动,而是在输入值变化时去抖动。您使用的是响应式表单还是模板驱动的?
标签: angular typescript rxjs angular-validation