【发布时间】:2021-09-13 10:25:48
【问题描述】:
每次单击按钮时,如果模型表单无效,则返回通知消息并且不继续创建用户(createUser)。
如果没有表单验证错误,它应该只继续返回 this.accountService.create
功能是否干净正确地实现?是否有一些导致问题的主要问题?谢谢。
我在哪里放置 checkInputs 验证,如果存在验证错误,则不应在 this.accountService.create 上继续
#html代码
<button #createUserBtn mat-flat-button color="primary" >Create
User</button>
#代码
@ViewChild('createUserBtn', { static: true, read: ElementRef })
button: ElementRef;
ngAfterViewInit(): void {
fromEvent(this.button.nativeElement, 'click')
.pipe(
tap(x => x),
exhaustMap(ev => {
return this.createUser();
})
)
.pipe(tap(x => x))
.subscribe(this.handleResponse());
}
createUser(): Observable<any> {
this.checkInputs();
this.isInProgress = true;
this.modelForm.markAllAsTouched();
return this.accountService.create(this.modelForm.value).pipe(
finalize(() => (this.isInProgress = false))
);
}
handleResponse(): any {
return {
next: res => {
this.notificationService.showSuccess('User has been created successfully.');
this._router.navigate(['settings/user']);
},
error: err => {
this.notificationService.showError('Something went wrong, Try again later.');
this.isInProgress = false;
},
complete: () => this.isInProgress = false
};
}
checkInputs() {
if(this.userStatus == 'USER_ON_NO_ACCOUNT') {
if(!this.modelForm.get('firstName').value) {
this.notificationService.showError('First Name is required.');
return;
}
if(!this.modelForm.get('lastName').value) {
this.notificationService.showError('Last Name is required.');
return;
}
if(!this.modelForm.get('companyName').value) {
this.notificationService.showError('Company Name is required.');
return;
}
}
if(!this.modelForm.get('roleId').value) {
this.notificationService.showError('Security Role is required.');
return;
}
if(this.modelForm.get('roleId').value && this.modelForm.get('roleId').value !== 7 && !this.modelForm.get('isSso').value) {
this.notificationService.showError('SSO is required.');
return;
}
if(this.modelForm.get('roleId').value && this.modelForm.get('isSso').value && this.modelForm.get('isSso').value ==='Yes' && !this.modelForm.get('ssocredentials').value) {
this.notificationService.showError('SSO Credential is required.');
return;
}
if(this.modelForm.get('isSso').value ==='No') {
this.modelForm.get('ssocredentials').setValue(null);
}
}
【问题讨论】:
标签: javascript angular typescript validation rxjs