所以我以另一种方式工作,灵感来自
Tomasz Kula answer
我创建了一个异步
Directive
实现
AsyncValidator
界面
我将额外的参数作为“对象”传递,在我的情况下,它看起来是这样的,
{
coupledControl: AbstractControl,
method: {
apiUrl: string
}
}
这是我的
directive
密码
import { Directive, forwardRef, Input } from '@angular/core';
import { NG_ASYNC_VALIDATORS, Validator, AbstractControl } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import { HttpClientService } from '../../../../../shared/services/httpclient.service';
import { HttpResponse } from '@angular/common/http';
import { IAsyncMethod } from './../interfaces/async-methods-interface';
@Directive({
// tslint:disable-next-line:directive-selector
selector: '[asyncValidator][formControlName], [asyncValidator][ngModel]',
providers: [
{
provide: NG_ASYNC_VALIDATORS,
useExisting: forwardRef(() => AsynValidatorDirective),
multi: true,
},
],
})
export class AsynValidatorDirective implements Validator {
@Input() asyncValidator: { coupledControl: AbstractControl; method: IAsyncMethod };
validate(
control: AbstractControl,
): Promise<{ [key: string]: any }> | Observable<{ [key: string]: any }> {
return this.validateIsExistAsync(control);
}
constructor(private httpService: HttpClientService) {}
validateIsExistAsync(control: AbstractControl) {
if (!control.pristine) {
const coupledControl: AbstractControl = this.asyncValidator.coupledControl;
const method: IAsyncMethod = this.asyncValidator.method;
return this.httpService
.getRequest(method.apiUrl + '?control=' + control.value + '&id=' + coupledControl.value)
.map((response: HttpResponse<boolean>) => {
return !response.body ? null : { asyncInvalid: true };
});
}
return Observable.of(null);
}
}
在我的
HTML
,则,
<input [asyncValidator]="{coupledControl: patientRestrationForm.get('patientFileId'), method: this.asyncMethods.validatePatientEmail }" [errorStateMatcher]="matcher" matInput autocomplete="off" formControlName="patientEmail">
在我的后端,我检查存在和匹配,简单的逻辑!
如果您有任何意见,