工作上解决的一种异步方法,angular8都发布了,也没去看
官方网站:https://angular.io/features
阿里的框架:https://ng.ant.design/docs/recommendation/zh
1.先构建一个表单
this.form = this.fb.group({ Cust_Moblie: [null, [Validators.compose([this.saleService.mobileRegxValidator])], [this.mobilequeValidator]], Cust_Tel: [null, [Validators.compose([this.saleService.telValidator])], [this.telValidator]], Cust_QQ: [null, [Validators.compose([this.saleService.qqValidator])], [this.qqValidator]], Cust_Wechat: [null, [Validators.compose([this.saleService.weChatValidator])], [this.weChatValidator]], Cust_Email: [null, [Validators.compose([this.saleService.emailValidator])], [this.emailValidator]], });
2.fromgroup的三个参数。官方文档还是要好好看的,当初就是面向百度编程,搜了好久才在百度上找到的解决方案
Cust_Email: [null, [Validators.compose([this.saleService.emailValidator])], [this.emailValidator]] 数组中第一项表示字段的默认值,null表示没有 数组第二项为一个数组,其中填写所需同步校验器的方法名,即不需要后台校验的校验方法 数组第三项仍为一个数组,其中填写所需异步校验器的方法名
第三点的异步验证会在同步验证通过之后再验证
3.同步邮箱验证
/**邮箱验证 */ emailValidator(control: FormControl) { const val = control.value; const mobieReg = regEx.email; const result = val == "" || val == null ? true : mobieReg.test(val); return result ? null : { Data: { info: '邮箱格式不正确' }, errors: true, required: true }; }
4.异步邮箱验证,判断是否已被注册
timers: any; /**异步调用方法 */ asycValidateFunction(observer, val, field1, field2, functionName, timers) { if (timers) { clearTimeout(this.timers) } if (val == "" || val == null) { observer.next(null); observer.complete(); } else { timers = setTimeout(() => { this.http.get(CUSTOMER_DIC_VALUE.Customer[functionName], { param: val, field1: field1, field2: field2 }).subscribe((data: any) => { if (data.Code === 'fail') { observer.next({ error: true, duplicated: true, Data: { info: data.Data } }); observer.complete(); } else { observer.next(null); observer.complete(); } }) }, 1000) } }
5.结合ng-zorror-ant的格式表现的验证提示信息
<nz-form-item class="mb-sm"> <nz-form-label [nzSm]="6" [nzXs]="24">Email</nz-form-label> <nz-form-control [nzSm]="10" [nzXs]="24" nzHasFeedback> <input nz-input formControlName="Cust_Email" placeHolder="Email"> <nz-form-explain *ngIf=" (form.get('Cust_Email')?.dirty && form.get('Cust_Email')?.errors) || form.get('Cust_Email')?.pending "> <ng-container *ngIf="form.get('Cust_Email')?.hasError('required')"> {{form.getError('Data','Cust_Email')?.info}} </ng-container> <ng-container *ngIf="form.get('Cust_Email')?.hasError('duplicated')"> {{form.getError('Data','Cust_Email')?.info}} </ng-container> <ng-container *ngIf="form.get('Cust_Email')?.pending"> 验证中... </ng-container> </nz-form-explain> </nz-form-control> </nz-form-item>
6.页面表现形式