在過去的幾天里,我一直試圖實作異步驗證。
服務代碼--
getUserIdToCheckDuplicate(userId:any):Observable< any> {
const url = ``; //url go here
return this.http.get<any> (url)。
}
組件代碼-
ngOnInit()。void {
this.form = this.fb.group({
userId: [''/span>, [Validators. required], [this.validate]]})
}
validate(control: AbstractControl)。) Observable<ValidationErrors | null> {
console.log(control.value)。
return of(control.value)
.pipe(
delay(10)。
switchMap((value) =>
this.userService.getUserIdToCheckDuplicate(value)。 pipe(map(x => {
return x.exists ? { exists: true } : null;
}))
)
);
}
Html代碼-
< mat-form-field appearance="outline"/span> fxFlex="1 1 calc(25% - 10px)" fxFlex. lt-md="1 1 calc(25% - 10px)"。
fxFlex.lt-sm="100%" fxFlex. xs="100%" class="from-color" *ngIf="!資料">
<mat-label class="標簽填充"> 用戶ID</mat-label>。
< input class="label-padding" formControlName="userId""userId" matInput placeholder="user ID" required />
<div style="color: red; font-weight: bold;"/span> *ngIf="userId. errors?.existence">Already
存在 !</div>已經存在!
</mat-form-field>/span>
在控制臺中- 控制臺錯誤
在控制臺中,當我在輸入中寫東西時,隨著每一個鍵的存盤,它列印出值,但之后告訴我值未定義!
。這個錯誤背后的原因是什么?我如何才能解決這個問題?它應該正常作業,以便async驗證器也能正常作業。
誰能幫助我解決這個問題?
誰能幫我解決這個問題呢?
uj5u.com熱心網友回復:
我已經設法在下面的stackblitz中再現了這個錯誤。
問題在于,this在這種情況下并沒有指代類
一個簡單的解決方案是簡單地使用箭頭函式進行驗證
validate = (control: AbstractControl)。) Observable<ValidationErrors | null> => {
console.log(control.value)。
return of(control.value)
.pipe(
delay(10)。
switchMap((value) =>
this.userService.getUserIdToCheckDuplicate(value)。 pipe(map(x => {
return x.exists ? { exists: true } : null;
}))
)
);
}
看這個 這里
uj5u.com熱心網友回復:
比這更簡單:
validate = (
control: AbstractControl: control.
): Observable<ValidationErrors | null> => {
return this.userService。 getUserIdToCheckDuplicate(control.value).pipe(
map(x => {
return x? { exists: true } : null;
})
);
(*)我想,如果沒有重復,你的服務會回傳null
參見stackblitz(以檢查,"fool "是重復的)如果你正在使用材料
<mat-form-field class="name"/span> appearance="outline"/span>>
< input matInput placeholder=="Name" formControlName="userId">
<mat-error *ngIf="form.get('userId')?.hasError('required')">/span>
姓名是必需的*。
</mat-error>/span>
<mat-error *ngIf="form.get('userId')?.hasError('existence')"/span>>
名稱重復
</mat-error>
<mat-hint *ngIf="form. get('userId')?.pending">驗證...</mat-hint>
</mat-form-field>/span>
但很好的是,"onblur "檢查錯誤(否則錯誤不會被顯示出來:在材料中,如果我們不使用自定義錯誤匹配器,只有在觸摸formControl(編輯和模糊)時才會顯示錯誤
。this. form = this.fb.group({
userId: [''/span>, [Validators. required], [this.validate]] ]
},{updateOn:'blur'})。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/311814.html
標籤:
