Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RXJS THROTTLETIME OPERATOR IS NOT WORKING IN ANGULAR-RX.JS

In my code I have function which calls the api. I want to throttle it someehow that the user cannot just keep on clicking the button to call the api.

Here is my function which calls the service

  public toggleFavorite(message: Message): void {
    const toggleMessageFavourite = new ToggleMessageFavouriteState(message.Id);
    this.messageService.toggleMessageFavourite(toggleMessageFavourite).subscribe(() => {
      message.Isfavourite = !message.Isfavourite;
    });
  }

In my service I have this code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

toggleMessageFavourite(model: ToggleMessageFavouriteState) {
    const url = `/Api/message/toggleMessageFavourite/`;
    return this.httpClient.post(url, model).pipe(
      throttleTime(5000)
    );
  }
}

I am expecting this function to throttle for 5 seconds before calling the next request.

>Solution :

It is not working since you are using the throttleTime operator in the pipe of a specific http request, that prevents more emission from the original observable but doesn’t prevent new http requests.

One of the ways to achieve what you need is something like this:

  toggledMessage$ = new Subject<toggleMessageFavourite >();

  public toggleFavorite(message: Message): void {
    const toggleMessageFavourite = new ToggleMessageFavouriteState(message.Id);
    
    this.toggledMessage.next(toggleMessageFavourite);
  
  }


 public exampleMethod(): void {
  this.toggledMessage$.pipe(throttleTime(5000))
  .subscribe(message => /* call api */ )
}

Of course, you need to call the exampleMethod initially in the ngOnInit.

You can also call the api in the switchMap operator and subscribe to the final result.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading