prevent user to click button until service response angular 7 rxjs

Viewed 2786

I am looking for efficient solution to avoid user to click the submit button again and again until they get response from backend API.

I have thought following solution but looking for any other ways to handle this.

  1. use loader which will disable whole html until we get some response.

  2. use exhaustmap to avoid multiple http calls

  3. use throttletime which will manually not allow user to click for specific time period.

Please guide me if there is any other solutions which we can use.

2 Answers

I would recommend to use exhaustMap() as primary solution in this case. In template:

<button (click)="submitForm()">Submit</button>

then in your component:

submit$: Subject<boolean> = new Subject();

constructor() {
  this.submit$.pipe(
    exhaustMap(() => this.http.get("api/endpoint"))
  ).subscribe(res => {});
}

submitForm() {
  this.submit$.next(true);
}

You click 'Submit' and all proceeding click events will be ignored by exhaustMap() operator until HttpClient instance returns response and get completed.

You can disable the button itself till you get a response by having a flag in your component's controller file.

// in component's controller

loading = false;
.
...
submit(): void {
  loading = true;
  this.someserive.getData().pipe(finalize(() => this.loading = false).subcribe(...
  .
  ....
}

// in component's template

<button [disabled]="loading" (click)="submit()">Submit</button>
Related