Add Validations Before Returning Observable In Angular
Everytime the button is clicke and if If modelform is invalid then return notification message and not proceed to creating a user (createUser). it should only proceed on returning
Solution 1:
You can add the invalid
check before this.accountService.create(this.modelForm.value)
, but you have to change the click
event handler to be like the following:
- There is no need to handle the
click
event this way, and instead, you can add the event handler directly from the template:
<button mat-flat-button color="primary" (click)="createUser()">
Create User
</button>
- There is no need to chain the
createUser
with the other observables, the and same forhandleResponse
. Instead, you can subscribe to theaccountService.create
function withincreateUser
method and handle thesuccess
andfail
within it also, like the following:
createUser(): void {
this.checkInputs();
this.isInProgress = true;
this.modelForm.markAllAsTouched();
// here you can check if the form is valid or not:
if (this.modelForm.invalid) return;
this.accountService.create(this.modelForm.value)
.pipe(
// take(1) is used to complete the observable after the result comes.
take(1),
catchError((err) => {
this.notificationService.showError(
'Something went wrong, Try again later.'
);
this.isInProgress = false;
return EMPTY;
}),
finalize(() => (this.isInProgress = false))
)
.subscribe((res) => {
this.notificationService.showSuccess(
'User has been created successfully.'
);
this._router.navigate(['settings/user']);
});
}
- You can remove the
ngAfterViewInit
block,handleResponse
method, and thebutton
@ViewChild
, because the abovecreateUser
will handle that, andcomplete
the observable directly after receiving the result from the service.
Post a Comment for "Add Validations Before Returning Observable In Angular"