Search code examples
angularrxjsthrottling

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

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.