1

I'm finding it hard to implement debounce on an HTTP request with Rxjs once a button is clicked. What I'm trying to achieve is when the button is click, it should wait for x seconds before the post is been made to the server.

btnClick() {
    this.loader = true;
    let send = "";
    send = this.checkForm.username.value;
    this.checkService
      .validate(send)
      .pipe(finalize(() => (this.loader = false)))
      .subscribe((response) => {
        console.log(response)
      });
  }

1 Answer 1

1

I would do something like calling a subject from the button click event handler to insert some debounce time, and then switchMap the post call

    btnClicked$: Subject <string> = new Subject<string>();

    ngOnInit(): void {
      this.btnClicked$.pipe(
        debounceTime(500),
        switchMap((send) => this.checkService.validate(send).pipe(
          finalize(() => (this.loader = false)))),
        take(1)
      ).subscribe()
    }

    btnClick(): void {
      this.btnClicked$.next(this.checkForm.username.value);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.