内部服务-
getUserIdToCheckDuplicate(userId:any):Observable<any>{
const url = ``; //url goes here
return this.http.get<any>(url);
}
内部组件-
ngOnInit(): void {
this.form = this.fb.group({
userId: ['', [Validators.required],[this.existingUserIdValidator()]]
}
get userId() {
return this.form.get("userId");
}
existingUserIdValidator(initialID: string = ""): AsyncValidatorFn {
return (
control: AbstractControl
):
| Promise<{ [key: string]: any } | null>
| Observable<{ [key: string]: any } | null> => {
if (control.value === initialID) {
return of(null);
}
else {
return control.valueChanges.pipe(
debounceTime(500),
take(1),
switchMap(_ =>
this.userService
.getUserIdToCheckDuplicate(control.value)
.pipe(
map(user =>
user ? { existingUserId: { value: control.value } } : null
)
)
)
);
}
};
}
里面的html-
<mat-form-field appearance="outline" fxFlex="1 1 calc(25% - 10px)" fxFlex.lt-md="1 1 calc(25% - 10px)"fxFlex.lt-sm="100%" fxFlex.xs="100%" class="from-color">
<mat-label class="label-padding">User ID</mat-label>
<input class="label-padding" formControlName="userId" matInput placeholder="User ID" required />
<div style="color: red; font-weight: bold;" *ngIf="userId.errors.existingUserId">Already Exists !</div>
</mat-form-field>
当我开始在输入字段中输入任何内容时,它会显示"Cannot read property 'existingUserId' of null"。
我已经按照各种不同的方式来执行这个异步验证。但就我而言,那些从未奏效!我不知道我在哪里犯错误!谁能帮我这个?