[Fixed] How to realize an action in a subscribe response in cases we get a correct response or an error?

Issue

I am trying to add a loading spinner to a login function. I’ve created a variable called "loading", and I want that this variable get false (and disapear in the html) when I obtain a response from the server (not before). I obtain the result with the next function, changing to false the variable in both responses (correct response and error response), but I would like to know if there is a cleaner way to do it.

Thank you!

login() {
    this.loading = true;
    let model: UserLogin = Object.assign({}, this.formGroup.value);
    this.accountService.login(model)
      .subscribe(
        token => {
          this.setToken(token);
          this.loading = false;        
        },
        error => {
          alert(this.errorService.manageError(error)[""]);
          this.loading = false;
        }
      );
    }

Solution

You could use the RxJS finalize operator. It’ll be triggered on both completion and error from the observable.

import { finalize } from 'rxjs/operators';

login() {
  this.loading = true;
  let model: UserLogin = Object.assign({}, this.formGroup.value);
  this.accountService.login(model).pipe(
    finalize(() => this.loading = false)
  ).subscribe(
    token => {
      this.setToken(token);
    },
    error => {
      alert(this.errorService.manageError(error)[""]);
    }
  );
}

Leave a Reply

(*) Required, Your email will not be published