防止相同的按钮频繁单击且角度可观察

时间:2018-07-28 08:49:07

标签: javascript angular rxjs observable

我有5个按钮列表,每次单击按钮我们都必须允许第一次记录该特定按钮。如果用户再次单击同一按钮,我们必须显示提示,提示您3秒钟后您必须等待3秒钟,他可能允许再次单击它。这必须适用于单独的5个按钮。

那么我们如何通过Observable实现这一目标。我们有fromevent方法,我不知道如何将其用于此特定任务。

<div *ngFor="let button of buttonlist">
  <button (click)="buttonClicked(button)">{{button}}</button>
</div>



buttonClicked(button) {
    for(var i=0; i<this.buttonlist.length; i++) {
      if(button == this.buttonlist[i]) {
        // here first time we have to allow if click it on same button again don't allow wait for 3 seconds then allow 
      }
    }
  }

您可以在这里找到工作示例https://stackblitz.com/edit/angular-6srmgj?file=src%2Fapp%2Fapp.component.ts

2 个答案:

答案 0 :(得分:3)

这就是你想要的code

<div *ngFor="let button of buttonlist">
  <button #btn>{{button}}</button>
</div> 

  buttonlist = ["button1", "button2", "button3", "button4", "button5"];
  @ViewChildren('btn') buttons:QueryList<any>;

  ngAfterViewInit() {
    this.buttons.forEach(button => {
      fromEvent(button.nativeElement, 'click').pipe(
        map(e => ({ e: e, t: setTimeout(() => console.log('wait...')) })),
        throttleTime(3000)
      ).subscribe((args: any) => {
        clearTimeout(args.t);
        console.log(args.e.target.innerHTML)
      });
    });
  }

答案 1 :(得分:0)

问题是

  

如果用户再次单击相同的按钮,我们必须显示提示,嘿,您必须在3秒后等待3秒,他可能允许再次单击它。

所以为了解决

  

我们必须显示提示,嘿,您必须等待3秒

问题的一部分,我建议扩展Hikmat的答案,并使用2个可观察值,其中一个包含throttleTime(),另一个不包含,如果需要,第一个将取消订阅后者,然后重新订阅:

@ViewChildren('btn') buttons: QueryList<any>;

private subs = [];
private subscriptions = new Subscription();;

buttonlist = ["button1", "button2", "button3", "button4", "button5"];

ngAfterViewInit() {
  this.buttons.forEach((button, ind) => {
    this.subscriptions.add(
      fromEvent(button.nativeElement, 'click').pipe(
        throttleTime(3000)
      ).subscribe((e: any) => {
        this.subs[ind].unsubscribe();
        setTimeout(_ => this.listenToClick(button, ind));
        console.log(`BUTTON # ${ind}: Now is good time to do something`);
      })
    );
    this.listenToClick(button, ind);
  });
}

ngOnDestroy() {
  // unsubscribe from throttled subscriptions
  this.subscriptions.unsubscribe();
  // unsubscribe from other subscriptions
  this.subs.map(sub => sub.unsubscribe());
}

private listenToClick(button, ind) {
  this.subs[ind] = fromEvent(button.nativeElement, 'click')
    .subscribe(res => console.log(`BUTTON # ${ind}: You have to wait for 3 secs`));
}

STACKBLITZ