用RxJs创建的Click事件比本机click事件发出的次数更多

问题描述 投票:1回答:1

我需要区分短点击(<400ms)和长点击(> 400ms)。我已经用RxJs实现了这两个事件,但是如果用户开始快速单击元素,则短按的发射方式应该比它产生的更多。

app.component.html

<button #button (click)="onBuiltInClickEvent()">Click</button>
<p>Method was called: {{ calledTimes }}</p>
<p>Native click was called: {{ nativeClick }}</p>

app.component.ts

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
  @ViewChild("button")
  public button: ElementRef;

  public calledTimes: number = 0;
  public nativeClick: number = 0;

  private mouseDown$: Observable<MouseEvent>;
  private mouseUp$: Observable<MouseEvent>;
  private click$: Observable<MouseEvent>;

  public ngAfterViewInit(): void {
    this.mouseDown$ = fromEvent(this.button.nativeElement, "mousedown");
    this.mouseUp$ = fromEvent(this.button.nativeElement, "mouseup");

    this.click$ = this.mouseDown$.pipe(
        flatMap(_ => {
            return this.mouseUp$.pipe(timeoutWith(400, EMPTY));
        })
    );

    this.click$.subscribe(_ => this.onClick());
  }

  private onClick(): void {
    this.calledTimes++;
  }

  public onBuiltInClickEvent(): void {
    this.nativeClick++;
  }
}

enter image description here

正在工作stackblitz

我需要区分短点击(<400ms)和长点击(> 400ms)。我已经用RxJs实现了这两个事件,但是如果用户开始单击,则短按发出的信号比应该发出的更多...

angular rxjs
1个回答
1
投票

flatMap在这种情况下不是合适的地图运算符。您不希望展平(或合并)内部可观察的对象。在这种情况下,一次只能激活一个内部订阅。因此,您可以使用switchMap运算符。

© www.soinside.com 2019 - 2024. All rights reserved.