Skip to content Skip to sidebar Skip to footer

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 for handleResponse. Instead, you can subscribe to the accountService.create function within createUser method and handle the success and fail 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 the button @ViewChild, because the above createUser will handle that, and complete the observable directly after receiving the result from the service.

Post a Comment for "Add Validations Before Returning Observable In Angular"