我想做的就是让用户在输入框中键入公司名称,然后它调用一个简单的后端api来检查他们键入的公司是否存在。
我的API调用工作良好;真";或";false";当用户键入值时成功。当它是假的/公司不存在时,它不会在屏幕上显示错误。
带有"************"就是它没有归还任何东西的地方。没有编译错误或运行时错误,只是在公司不存在时不会显示mat错误。
考虑到代码的行数,如果你认为这是一个令人生畏的问题,我不怪你,我一直在努力找出一些看似简单的问题,花了将近6个小时。
我的报告-view.component.ts文件:
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(
control: FormControl | null,
form: FormGroupDirective | NgForm | null
): boolean {
//console.log("blah");
const invalidCtrl = !!(control && control.invalid);
const invalidParent = !!(
control &&
control.parent &&
control.parent.invalid
);
return invalidCtrl || invalidParent;
}
}
@Component({
selector: 'app-reports-view',
templateUrl: './reports-view.component.html',
styleUrls: ['./reports-view.component.scss']
})
export class ReportsViewComponent implements OnInit {
matcher = new MyErrorStateMatcher();
CompanyNameInputForm: FormGroup;
companyNameValidator() {
return (form: FormGroup) => {
this.reportsPageService.doesCompanyNameExist(form.controls.companyName.value).subscribe((data) => {
console.log(data);
if (form.controls.companyName.value === "") {
console.log("returning null inside if");
return null;
}
else if (data==false) {
console.log("company name does not exist");
******************return { invalidCompanyName: true };******************
}
console.log("returning null at end");
return null;
});
}
}
ngOnInit() {
this.CompanyNameInputForm = this.formBuilder.group(
{
companyName: [""]
},
{ validator: this.companyNameValidator() }
);
this.CompanyNameInputForm.setValue({
companyName: this.companyName
});
}
constructor(private routingService: RoutingService, public reportsPageService: ReportsPageService,
private formBuilder: FormBuilder) {
this.BASE_URL = routingService.getBaseUrl();
}
}
在我的服务文件中:
doesCompanyNameExist(companyName: string):any {
return this.http.post(`${this.BASE_URL}/RESTAPI/reports/doesCompanyNameExist?companyName=${companyName}`,
this.httpOptions);
}
html:
<form [formGroup]="CompanyNameInputForm">
<mat-form-field>
<input matInput placeholder="Company name" type="text" formControlName="companyName" [errorStateMatcher]="matcher">
<mat-error *ngIf="CompanyNameInputForm.hasError('invalidCompanyName')">Company does not exist
</mat-error>
</mat-form-field>
</form>
您正试图同步验证表单组,而验证结果是在异步检查您的服务后得出的。
您需要创建一个AsyncValidator并更新FormGroup的配置。
这意味着你必须建立这样的团队:
this.CompanyNameInputForm = this.formBuilder.group(
{
companyName: [""],
},
{ asyncValidator: this.companyNameValidator }
);
然后您需要更新验证器方法:
companyNameValidator(form: FormGroup): Observable<ValidationErrors | null> {
return this.reportsPageService.doesCompanyNameExist(form.controls.companyName.value)
.pipe(map((data) => {
console.log(data);
if (form.controls.companyName.value === "") {
console.log("returning null inside if");
return null;
}
else if (data == false) {
console.log("company name does not exist");
return { invalidCompanyName: true };
}
console.log("returning null at end");
return null;
}));
}