避免用户连续的重复点击、一定时间的重复提交都可以参考
从这里开始
- 自定义指令 ThrottleClickDirective
import { Directive, EventEmitter, HostListener, OnInit, Output, OnDestroy } from '@angular/core';
import { Subject, Subscription } from 'rxjs';
import { throttleTime } from 'rxjs/operators';
/**
* 点击节流器:避免连续点击
*/
@Directive({
selector: '[directive-throttle]'
})
export class ThrottleClickDirective implements OnInit, OnDestroy {
// 一定的时间内只执行第一个事件
private THROTTLE_TIME: number = 1000;
private subject = new Subject<MouseEvent>();
private click: Subscription;
// 事件方法
@Output() throttleClick = new EventEmitter();
constructor() { }
ngOnInit(): void {
const result = this.subject.pipe(
throttleTime(this.THROTTLE_TIME)
);
this.click = result.subscribe(e => {
this.throttleClick.emit(e)
})
}
ngOnDestroy() {
this.click.unsubscribe();
}
@HostListener('click', ['$event'])
onClick(evt: MouseEvent) {
this.subject.next(evt);
}
}
- 使用方法
<button type="submit" directive-throttle (throttleClick)="search()">查询</button>
附录
- throttleTime
在一定时间间隔内,忽略执行后续动作。官方在这里