【发布时间】:2017-03-10 20:52:49
【问题描述】:
我正在尝试通过 FormControl 添加异步验证,并且每次按键都会收到多个响应。每次我从表单控件中键入/删除一个字符时,都会发出一个额外的请求。
basics.component.ts
export class TrainingModuleBasicsComponent implements OnInit, StepperItem<TrainingModule> {
trainingModule: FormGroup;
errorMessages: Object;
formErrors: Object;
model: TrainingModule;
constructor(private fb: FormBuilder, private trainingModuleService: TrainingModuleService) { }
ngOnInit() {
this.buildForm();
this.buildValidation();
}
buildForm(): void {
const codeRegex = '[a-zA-Z0-9-_]*';
this.trainingModule = this.fb.group({
moduleCode: [this.model.moduleCode, Validators.pattern(codeRegex), [this.validateDuplicateCourseCode.bind(this)]],
title: [this.model.title, Validators.required],
description: [this.model.description]
});
}
private validateDuplicateCourseCode(control: AbstractControl) {
return new Observable((obs: any) => {
control.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.switchMap(value => this.trainingModuleService.verifyCourseCode(value))
.subscribe(
data => {
console.log('request made');
if (!data.error) {
obs.next({'duplicateCourseCode': true});
obs.complete();
} else {
obs.next(null);
obs.complete();
}
}
);
});
}
training-module.service.ts
@Injectable()
export class TrainingModuleService {
constructor(private http: Http) { }
verifyCourseCode(courseCode: string): Observable<any> {
return this.http.get(environment.rlmsApi + '/Modules/Code/' + courseCode,
new RequestOptions({ headers: new RlmsHeaders() })
)
.map(res => Observable.of(res.json()))
.catch(e => Observable.of(e.json()));
}
【问题讨论】:
-
你的问题是什么
-
validateDuplicateCourseCode 函数在第一次按键时调用 3 次。再按一次按键后,该函数会进行 4 次调用。在另一次按键之后,它会拨打 5 次电话,并以这种方式继续。如果用户在按键后暂停(debounceTime),我只希望它每次按键发出一个请求。相反,似乎直到 debounceTime 之后才进行调用,但它们都是在之后调用的。
-
@JosephWilliams 你是怎么解决这个问题的?我实际上有一个类似的问题。当我的表单显示多个调用时。
标签: javascript angular rxjs observable