A
A
Andrey Kharitonov2021-12-22 07:51:42
Angular
Andrey Kharitonov, 2021-12-22 07:51:42

How to subscribe to a variable change and execute the function call once for the last element?

In html, when a div is clicked, a variable is changed and each time a change is made, a request to the server is made. How can I make the request to the server be sent only once? For example, I click 10 times - and the call is only one for the current (last) value. Now the call to the server is 10 times, although the variable is what I need.

html:

<div class="btn btn-mmk-color" 
                          id="next" 
                          mwlCalendarNextView [view]="view" 
                          [(viewDate)]="viewDate"
                          (click)="activeDayisOpenFalse();" 
                    >
                      <i id="next2"   class="fas fa-angle-double-right"></i>
                  </div>

component.ts:
time$ : BehaviorSubject<number> = new BehaviorSubject(0);



activeDayisOpenFalse() {
    console.log('click');
    this.activeDayIsOpen = false;
    
    /*this.getCalendar();
    */
   
    this.time$.next(this.viewDate.getMonth() + 1 );

    this.time$.subscribe(
      (v)=> {console.log(v)} // здесь логи выводятся 10 раз, хочу сюда вызов на сервер поставить
      
    )
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
lssssssssssl, 2021-12-22
@lsssssssssl

https://www.learnrxjs.io/learn-rxjs/operators/tran...
If you click 10 times, 10 requests should go. The only question is that you will probably no longer need the first 9 results. And switchMapthat will help just that.
But if you fundamentally need it to be impossible to poke 10 times, hang disabled on the button until the result of the first click comes.

E
eRKa, 2021-12-22
@kttotto

Depends on what the "last click" is and how you define it as the last. If you mean that you can quickly click several times on an element and a send is triggered for each click, but you need it only once, after the "last click in the group of quick clicks", then there is an operator https://rxjs.dev for this /api/operators/debounce . The event will pass only when the specified time passes after the click. For example, this is used when typing in the search line: we do not need a request to enter each letter (but they type quickly), a pause will be expected between a set of characters, as soon as it appears, a request will occur.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question