问题描述
我很难让 distinctUntilChanged
在下一个场景中工作.我做了一个异步验证器,它使用一个服务来检查用户是否存在给定的用户名.此验证器作为指令绑定到输入.
I'm having a hard time making distinctUntilChanged
work in this next scenario. I made an asynchronous validator, which uses a service to check if a user exists with the given username. This validator is bound, as a directive, to an input.
class ValidateUniqueUsernameDirective implements AsyncValidator {
constructor(private userService: UserService) {}
validate(
control: AbstractControl
): Promise<ValidationErrors> | Observable<ValidationErrors> {
return control.valueChanges.pipe(
debounceTime(1000),
tap(value => {
debugger;
console.log(value);
}),
distinctUntilChanged(),
switchMap(value => {
return this.userService.getUserByUsername(value).pipe(
map(user => {
const usernameIsAvailable = user === undefined;
return usernameIsAvailable
? null
: { usernameAvailability: { value: control.value } };
})
);
})
);
}
}
调用服务会导致网络请求,所以我取消了验证,为了进一步减少它们,我尝试添加 distinctUntilChanged
,这样,正如用户 @Kld 解释的那样 此处,用户在去抖动时间内返回之前的值不会触发一个新的请求.然而,事实并非如此.我不明白发生了什么,因为挖掘的价值似乎是一样的.
Calling the service results in network requests, so I debounced the validation, and, to further lessen them, I tried adding distinctUntilChanged
, so that, as user @Kld explains here, user changes within the debounce time back to the previous value wouldn't trigger a new request. However, that's not what's happening. I don't understand what's happening, as the tapped value seems to be the same.
我正在使用 Angular 6,使用 RxJS 6.感谢您的帮助!
I'm on Angular 6, using RxJS 6. Thank you for your help!
推荐答案
保持简单:
class ValidateUniqueUsernameDirective implements AsyncValidator {
private lastValue=null;
private lastResult=null;
constructor(private userService: UserService) {}
validate(
control: AbstractControl
): Promise<ValidationErrors> | Observable<ValidationErrors> {
if(lastValue!==control.value){
//do your validation and save result
}else{
// return last result or clear error state
}
}
}
您还可以添加超时以在用户停止输入等后执行请求
You can also add timeouts to perform request after user stops typing etc.
这篇关于FormControl distinctUntilChanged() 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!