Search code examples
angularangular-httpclient

View variable not updating from error handler code when using httpclient


I have an auth service, that I use to do login to my application.

This is handled in the login() function in my login component:

  public login() {

    const val = this.form.value;

    if (!this.email.invalid && !this.password.invalid) {
      this.authService.login(val.email, val.password)
        .pipe(
          catchError(this.handleError)
        )
        .subscribe(
          data => {
            this.jwtToken = data;
          }
        );
    }
  }

If some error occurs (e.g. a 401 unauthorized) then the handleError function is called, and I get more specific information from within that function:

private handleError(error: HttpErrorResponse) {
    if (error.status === 0) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
      this.loginStatus =
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`
      console.log("Setting it: " + this.loginStatus)
    }
    // Return an observable with a user-facing error message.
    return throwError(
      'Something bad happened; please try again later.');
  }

In my .html file, I put {{loginStatus}} to output the text set in the handleError function.

The issue I have is that the loginStatus display is never updated in the html view. If I assign it a value in the subscribe part - it is updated fine, but it seems that it is not updated when I assign it in the catchError handler. I can see in the console that it is set fine in the handleError function, but the view never gets updated.

Any ideas on why and what could be done if I want to display some more specific info to the user after the handleError function runs?


Solution

  • The this context is being lost when the error handler is called

    Try calling the error handler from with an arrow function:

    catchError((err) => {
         return this.handleError(err)
    })