简体   繁体   中英

Angular 2, throttleTime on observable from subject

Im trying to make throttleTime take effect, but for some reason it does not kick in. I have the following:

// Class Properties    
private calendarPeriodSubject: Subject<x> = new Subject<x>();
private calendarPeriodObservable$ = this.calendarPeriodSubject.asObservable();


// Throttling fails here (Inside constructor):
const calendarPeriodSubscription = this.calendarPeriodObservable$.pipe(throttleTime(750)).subscribe(async (calendar: x) => {
    // Do http stuff here
  }
});

The subject gets called like this:

this.calendarPeriodSubject.next(x);

I also tried with:

this.calendarPeriodSubject.pipe(throttleTime(1000)).subscribe({next: (x) => x});

I would like to process the FIRST time, and the following clicks should not have any effect before after ieg 750ms - To prevent the server from getting spammed basically.

Anyone has any idea?

Thanks!

The problem is that you are using the wrong operator for your use case. The way I understand your explanation you want to send through your first call and stop any further calls to your Server for some amount of ms. But what throttleTime(sec) does is simply put a timer on the action and execute it sec ms later. So you server will still be spammed, just a few ms later.

Your case screams debounceTime() for me. debounceTime docu

This disables any further data to be passed though the Observable for the specified time after a value has been emitted.

Therefore your code should be fine if you use something like:

const calendarPeriodSubscription = 
this.calendarPeriodObservable$.pipe(debounceTime(750)).subscribe((calendar: x) => {
    // Stuff with returned data
});    

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