本週寫的項目須要對名稱進行驗重,採用的是angular的異步驗證器的方式.java
首先要查詢數據庫表中是否存在相同名稱,須要一個驗證重複的後臺接口:數據庫
/** * @description 是否存在姓名 * @param name 姓名 * @return java.lang.Boolean * @author htx * @date 下午7:19 19-3-28 **/ @GetMapping("existByName/{name}") public Boolean existByName(@PathVariable String name) { return majorService.existsByName(name); }
只須要查詢數據庫中是否存在該名稱,返回true或false便可.app
由於在編輯和添加時都須要驗證,因而就把獲取驗證方法寫在了服務裏,從服務裏獲取驗證方法:異步
/** * @description 獲取名稱是否重複的驗證器 * @param name 當name存在時 默認跳過name(用於編輯可能保留原名稱) * @return AsyncValidatorFn 異步驗證器 * @author htx * @date 下午7:53 19-3-28 **/ getValidatorNameExistFn(): AsyncValidatorFn { return (control: AbstractControl): Observable<ValidationErrors | null> => { return this.existByName(control.value).pipe( map(exist => (exist ? {exist: true} : null)), catchError(() => null) ); }; } /** * @description 是否存在相同編號名稱 * @param name 名稱 * @author htx * @date 下午7:45 19-3-28 **/ existByName(name: string): Observable<boolean> { return this.http.get<boolean>(this.baseUrl + '/existByName/' + name); }
執行getValidatorNameExistFn()方法就會獲取驗證名字是否重複的異步驗證方法,由於AsyncValidatorFn接口要求返回的是
Observable<ValidationErrors | null>,但咱們後臺接口返回的是true或false,所以須要用map操做符進行轉換.
在創建控件的時候將驗證方法加入異步驗證便可:ui
this.validateForm = this.fb.group({ name: [null, [Validators.required], [this.majorService.getValidatorNameExistFn()]], number: [null, [Validators.required], [this.majorService.getValidatorNumberExistFn()]], college: [null], teacherList: [null] });
v層中增長提示信息:this
<nz-form-explain *ngIf="validateForm.get('name').dirty && validateForm.get('name').errors?.exist">專業名稱已存在! </nz-form-explain>