我有一個表單,管理員可以在其中創建新用戶。我想驗證用戶名欄位是唯一的。我創建了一個 uniqueUserNameValidator,但是這個函式總是回傳 null。我相信這是因為服務是異步方法。在繼續之前我需要異步的結果我試圖添加一個等待錯誤這也會產生奇怪的問題。我該如何解決這個問題謝謝你的幫助。
這是我想使用驗證器的地方
this.userService.getEmployeeById(this.employeeId).subscribe(result => {
this.employee = result;
this.employeeDetailForm = new FormGroup({
userName: new FormControl(this.employee.userName, [Validators.required, this.uniqueUserNameValidator.bind(this)])
});
這是我的驗證器
private uniqueUserNameValidator(control: FormControl): { [s: string]: boolean } {
this.employee.userName = control.value;
var userExists: boolean;
this.userService.checkIfEmployeeUserNameExists(this.employee).subscribe(data => {
userExists = data;
})
if (userExists) {
return { userExists: true };
}
return null;
}
這是有問題的服務
checkIfEmployeeUserNameExists(employee: Employee) {
return this.http.put<boolean>(this.baseUrl 'employees/isUserNameUnique', employee)
}
uj5u.com熱心網友回復:
正如其他用戶在評論中已經指出的那樣,您應該使用異步驗證器來獲得您想要的行為。創建新控制元件時,可以validatorOrOpts作為第二個引數傳入。這使您可以更好地控制您可以設定的驗證器。
this.employeeDetailForm = new FormGroup({
userName: new FormControl(this.employee.userName, {
validators: [Validators.required],
asyncValidators: [this.partnerCodeAvailabilityValidator.bind(this)]
})
});
partnerCodeAvailabilityValidator應該是這樣的:
private partnerCodeAvailabilityValidator(
control: AbstractControl
): Observable<ValidationErrors | null> {
this.employee.userName = control.value;
return this.userService
.checkIfEmployeeUserNameExists(this.employee)
.pipe(map((data) => data ? ({ userExists: data }) : null));
}
或者,您可以構建一個指令并實作AsyncValidator介面,以防您想將它與模板驅動的表單一起使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/454279.html
下一篇:建構式的打字稿型別是什么?
