我从Web服务调用返回后,自定义FormGroup验证器无法正确更新验证器错误状态,该调用检查displayName是否已在使用中。在下面的代码中,我知道我的html代码正在工作,因为当displayName输入为空时,组件的validateDisplayName函数显示“ Display Name is used used”。然后,当您开始输入字母时,将调用Web服务以开始验证第三个字母上的条目-然后消息消失,当我键入与数据库中的一个匹配的displayName时,Web服务将正确返回true,但是调用不会导致显示错误。我知道它与Web服务返回的Promise有关,但是我找不到解决方案。component.tsngOnInit() { this.dnFormGroup = this.formBuilder.group({ displayName: ['', this.validateDisplayName.bind(this)] });}public validateDisplayName(control: AbstractControl): any { console.log("RegisterComponent validateDisplayName - ENTRY"); if(control.value.length >= 3) { return this.authService.validateDisplayName(control.value).then( (res) => { console.log("RegisterComponent validateDisplayName - res: " +res); if(res) { console.log("RegisterComponent validateDisplayName - displayName already used"); return { displayNameTaken: true }; } else { console.log("RegisterComponent validateDisplayName - - displayName can be used"); return null; } }, (err) => { console.log("RegisterComponent validateDisplayName - err: " +err); return { displayNameTaken: true }; }); } console.log("RegisterComponent validateDisplayName - ############## EXIT"); return { displayNameTaken: true };}组件服务public validateDisplayName(displayName: string) { console.log("AuthService validateDisplayName - displayName: " +displayName); return this.http .get(environment.server_url +"profile_cont/displaynameexists/" +displayName +"/") .toPromise() .then( (response) => { const existsBool = response.json(); console.log("AuthService validateDisplayName - existsBool: " +existsBool); return existsBool; }, (error) => { console.log("AuthService validateDisplayName - error: " +error); return true; });}component.html <form [formGroup]="dnFormGroup"> <fieldset> <div class="row"> <section class="col col-6"> <label class="input"> <i class="icon-append fa fa-user"></i> <input formControlName="displayName" type="text" minlength="3" maxlength="10" placeholder="Display name"> <b class="tooltip tooltip-top-right"> <i class="fa fa-user txt-color-teal"></i> Please provide a 3 to 10 char name for site display purposes.</b> </label> <div *ngIf="dnFormGroup.get('displayName').hasError && dnFormGroup.get('displayName').hasError('displayNameTaken')"> Display Name is already used </div> </section> </div> </fieldset></form>谢谢,鲍勃 最佳答案 异步验证器必须是第三个参数,请尝试:this.dnFormGroup = this.formBuilder.group({ displayName: ['', null, this.validateDisplayName.bind(this)]});关于javascript - Angular 5 FormGroup验证器Web服务结果未触发ngIF hasError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54770089/
10-11 13:09