【发布时间】:2019-06-01 08:02:05
【问题描述】:
我正在尝试为 Angular 7 中的多个复选框应用去抖动时间。这个想法是将 api 调用延迟 x 秒,以便更好地执行应用程序(选中/取消选中复选框会调用对 API 的调用)。
每个复选框对应一个过滤器,在选中/取消选中时发送到后端,并确定从服务器返回的结果。我尝试使用此处提到的文章中建议的自定义去抖动指令, https://coryrylan.com/blog/creating-a-custom-debounce-click-directive-in-angular
问题解决了单个输入字段的去抖动问题,在我的情况下,如果我在去抖动时间内多次选中和取消选中单个复选框,无论我点击多少次,都只会调用后端。但我的问题是选中/取消选中多个复选框,并且在去抖动时间内只向 API 发出一个请求。 现在,每次单击未解决我的问题的复选框时都会调用 api。
以下是我使用的指令,类似于文章中的示例:
import { Output, EventEmitter, OnInit, OnDestroy, Directive, ElementRef } from '@angular/core';
import { debounceTime } from 'rxjs/operators';
import { HostListener } from '@angular/core';
import { Subscription, Subject } from 'rxjs';
@Directive({
selector: '[appDebounceClick]'
})
export class DebounceDirective implements OnInit, OnDestroy{
@Output() debounceClick = new EventEmitter();
private clicks = new Subject();
private subscription: Subscription;
constructor(private elementRef: ElementRef) { }
ngOnInit() {
this.subscription = this.clicks.pipe(
debounceTime(2000)
).subscribe(e => this.debounceClick.emit(e));
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
@HostListener('change', ['$event'])
clickEvent(event) {
this.clicks.next(event);
}
}
以下是我模板中的代码:
<ng-container *ngFor="let checkbox of checkboxList">
<mat-checkbox *ngIf="checkbox.name == 'test'" [(ngModel)]="checkbox.selected" appDebounceClick (debounceClick)="onChange($event,checkbox)" >
{{checkbox.name}}
</mat-checkbox>
</ng-container>
我觉得这里的问题是指令应用于每个复选框,这反过来又创建了一个新的 Observable/Subject,它只与单个复选框相关联。我认为应该只有一个主题可供订阅复选框上的点击事件,但我不完全确定如何实现它。非常感谢您对此问题的任何想法或解决此问题的任何更好的想法。
【问题讨论】:
标签: javascript angular typescript