Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Reactive Forms form control valueChanges stops listening on error

I have a registration form where I am using valueChanges listener on a form control and makes call to http service that posts to server if this value already exists, e.g. email and user name. If the value exists already on the server, then a status code 403 is returned. I am catching and handling this error by presenting a message to the user, but my problem is the valueChanges listener stops listening, so if I just change the form value, then this code is idle. Can I get the listener to continue even after the error? Should I be handling this another way? Thank you.

Here is listener code:

    this.watchEmailSub = this.registerForm.controls.email.valueChanges.pipe(
      debounceTime(500),
      distinctUntilChanged(),
      switchMap(v =>
        this.regService.checkRegistrationValueExists('Email', v, this.registerForm.controls.email.valid)
      )
    ).subscribe(returnValue => {
        this.registerEmailError = null;
        console.log('returnValue.message = ', returnValue.message);
      },
      (error) => {
        console.warn('Error = ', error);
        this.registerEmailError = 'This email already exists';
      }
    );

HTTP service code:

  checkRegistrationValueExists(type: string, value: string, formControlValid: boolean): Observable<any> {
    // Code removed here that defines checkValueExistsUrl & checkValueExistsBody
    if (formControlValid) {
      return this.http.post<string>(checkValueExistsUrl, checkValueExistsBody);
    }
    return of({ message: `${type} invalid` });
  }
like image 411
Larry King Avatar asked Sep 04 '26 13:09

Larry King


1 Answers

You can use catchError and swallow the error to prevent this:

this.watchEmailSub = this.registerForm.controls.email.valueChanges.pipe(
  debounceTime(500),
  distinctUntilChanged(),
  switchMap(v =>
    this.regService.checkRegistrationValueExists('Email', v, this.registerForm.controls.email.valid).pipe(
      catchError(error => {
        this.registerEmailError = 'This email already exists';
        return EMPTY;
      })
    )
  )
).subscribe(returnValue => {
    this.registerEmailError = null;
    console.log('returnValue.message = ', returnValue.message);
  },
  (error) => {
    console.warn('shouldn't be here');
  }
);

IMO 403 shouldn't be thrown here. 403 is inapropriate in any event, as 403 means unauthorized to view this information, if any error, it'd be a 400. Beyond that though, this is an API endpoint specifically checking availability. Error codes mean something went wrong. Nothing went wrong here, it checked and returned your answer successfully, yes it exists or no it doesn't.

like image 200
bryan60 Avatar answered Sep 06 '26 07:09

bryan60



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!