如何在多个单击事件上创建队列

时间:2018-06-04 14:52:35

标签: javascript angular events onclick rxjs

关于Angular 4 / Typescript中我现在面对的这个非常具体的情况,我有一个问题。我有2个按钮(例如:增加:" +"和减少:" - "),booth有onClick事件来改变当前数字的值。

每次点击我都会进行API调用以更新Backend上的新数字值。如果用户非常快速地多次点击(例如,在不到1秒的时间内从0增加到14次,我会发送14次调用)。

我想存储增加的号码,并在上次通话300分钟后发送电话。表格表示:

|-----------------------------------------------------------------------|
| Clicks   | 1 . 2 . 3 . 4 . 5 . 6 . 7 . 8 . 9 . 10 . 11 . 12 . 13 . 14 |
|-----------------------------------------------------------------------|
| Time     | 0ms ......... 300ms .............. 600ms ............ final|
|-----------------------------------------------------------------------|
| Api call | ............ send(5) ........... send(10) ........ send(14)|
|-----------------------------------------------------------------------|

我在google上搜索这个但没有找到。

2 个答案:

答案 0 :(得分:1)

here is live demo at CodeSandbox and the minimal code representation is below.

Overall the throttleTime emits the latest value when specified duration has passed. rxjs docs

I hope this will help you out.

import { Component } from "@angular/core";

import { throttleTime } from "rxjs/operators";

import { Subject } from "rxjs";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  dumySubject = new Subject();
  clicker = 0;
  calls = [];

  constructor() {}

  ngOnInit() {
    this.dumySubject.pipe(throttleTime(300)).subscribe(() => {
      this.calls.push(this.clicker);
    });
  }

  clickFunc() {
    this.clicker++;
    this.dumySubject.next(this.clicker);
  }
}

答案 1 :(得分:1)

您可以尝试将debounceTime和distinctUntilChanged结合起来:https://www.learnrxjs.io/operators/filtering/distinctuntilchanged.html

以下示例仅在不同于最后一个值时才会发出值,每300毫秒轮询一次。您可以在按钮上调用next()函数,并在订阅中进行API调用。

import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {


    value$ = new Subject<string>();

    constructor() {}   

    ngOnInit() {        
        this.value$
            .pipe(debounceTime(300))
            .pipe(distinctUntilChanged())
            .subscribe(result => {
                // call api
            });
    }
}