Angular5 避免重复请求

避免用户连续的重复点击、一定时间的重复提交都可以参考

从这里开始

  1. 自定义指令 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);
  }
}

  1. 使用方法
<button type="submit" directive-throttle (throttleClick)="search()">查询</button>

附录

  1. throttleTime
    在一定时间间隔内,忽略执行后续动作。官方在这里
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值