【发布时间】:2019-04-08 17:21:55
【问题描述】:
我有一个从我的数据库中检索数据的搜索栏,只要搜索成功,检索到的数据就会填充一个 mat 表,到目前为止一切都很好并且可以正常工作。
我面临的问题是,由于用户提供了无效信息,该搜索无法从数据库中检索到任何内容。
当我向输入表单提供数据并且 HTTP 响应失败时,应该会立即触发 mat-error,但是只有在我单击搜索按钮两次时才会发生这种情况。
这是我的代码:
MyComponent.component.ts
public inputForm: FormControl;
ngOnInit() {
this.inputForm = new FormControl('');
}
private searchForReturnByOrderNumber(value) {
this.rest.getOrderByNumber(value).subscribe((orderNrData: {}) => {
if (Object.entries(orderNrData).length !== 0) {
this.rest.getReturnByOrderNumber(value).subscribe((returnOrdNrData: Return[]) => {
if (Object.entries(returnOrdNrData).length !== 0) {
this.returns = returnOrdNrData;
this.setReturns();
} else {
this.openDialog(orderNrData, returnOrdNrData);
}
}, error => {
if (error.status === 404) {
this.openDialog(orderNrData, []);
}
});
} else {
this.inputForm.setErrors({ 'invalid': true });
}
}, error => {
this.inputForm.setErrors({ 'invalid': true });
});
}
private isInputInvalid() {
if (this.inputForm.hasError('invalid')) {
return true;
}
return false;
}
private getErrorMessage() {
return this.inputForm.invalid ? 'Invalid Search!' : '';
}
MyComponent.component.html
<div class="row">
<div class="col-2"></div>
<div class="col-8 search-div">
<mat-form-field class="search-form-field" appearance="outline">
<mat-label>Search</mat-label>
<input matInput class="search-input" placeholder="Ex: EU030327" [formControl]="inputForm" #searchInput>
<mat-error *ngIf="isInputInvalid()">{{ getErrorMessage() }}</mat-error>
</mat-form-field>
<span matSuffix>
<button mat-flat-button class="search-btn" color="accent" [disabled]="isInputInvalid()"
(click)="searchForReturnByOrderNumber(searchInput.value)"><i class="fa fa-search"></i></button>
</span>
</div>
<div class="col-2"></div>
</div>
如果我输入一些无效数据(数据库中不存在的数据)并按下我的“search-btn”,我的 mat 错误将不会出现,只有当我再次按下按钮时。
我已经调试过了,代码正确输入了预期的代码:
} else {
this.inputForm.setErrors({ 'invalid': true });
}
它将 inputForm 设置为无效,但直到我再次单击该按钮才会出现 mat-error...
有谁知道可能出了什么问题?
谢谢!
【问题讨论】:
标签: javascript node.js angular typescript