角度点击反跳 [英] Angular click debounce

查看:101
本文介绍了角度点击反跳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模板中,我有一个字段和两个按钮:

In my template I have a field and two buttons:

<div class="btn-plus" (click)="add(1)"> - </div>
<div class="txt"> {{ myValue }} </div>
<div class="btn-minus" (click)="add(-1)"> + </div>

在组件.ts文件中,我有:

In my component .ts file I have:

add(num) {
    this.myValue +=num;
    this.update(); // async function which will send PUT request
}

this.update()函数将 myValue 放在大JSON对象的适当字段中,并将其发送到服务器。

The this.update() function puts myValue in the proper field in a big JSON object and sends it to a server.

问题:当用户在短时间内单击按钮正负10次后,请求将被发送10次。但是我只想发送一次请求-最终点击后0.5秒。 操作方法

Problem: When a user clicks 10x in a short period of time on button plus/minus, then a request will be send 10 times. But I want to send a request only once - 0.5 sec after last click. How to do it?

推荐答案

使用 takeUntil 运算符:

Use the takeUntil operator :

export class AppComponent  {
  name = 'Angular';

  calls = new Subject();

  service = {
    getData: () => of({ id: 1 }).pipe(delay(500)),
  };

  click() {
    this.calls.next(true);
    this.service.getData().pipe(
      takeUntil(this.calls),
    ).subscribe(res => console.log(res));
  }
}

Stackblitz (打开您的控制台以查看日志)

Stackblitz (open your console to check the logs)

这篇关于角度点击反跳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆