简体   繁体   中英

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.

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.

You're creating a new observable on every call to toggleMessageFavourite .

throttleTime works on the values sent by an observable.

class Foo {
  subject$ = new Subject<string>();

  public constructor() {
    this.subject$.pipe(
      throttleTime(5000),
      switchMap((id: string) => {
        const toggleMessageFavourite = new ToggleMessageFavouriteState(message.Id);
        this.messageService.toggleMessageFavourite(toggleMessageFavourite)
      }).subscribe(() => {
        // 
      });
    )
  }

  public toggleFavorite(message: Message): void {
    this.subject$.next(message.Id);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM