这是对已接受答案的补充答案,并深入探讨了有关实际放置去抖动的位置的更多细节。
当使用FormControls 时,由于 valueChanges (example) 的存在很容易去抖动:
this.searchField.valueChanges
.debounceTime(400)
.switchMap(term => this.searchService.search(term))
.subscribe((result) => {
this.result = result.items
});
这依赖于switchMap 函数,该函数取消现有调用并保留最新调用。
使用自定义控件时,取消通常需要自定义代码(example for a Kendo control 不会发出更改,但依赖于事件):
应用去抖动的值更改指令后
import { Directive, Input, HostListener, OnDestroy, Output, EventEmitter } from '@angular/core';
import { Subject, Subscription } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
@Directive({
selector: '[afterValueChanged]'
})
export class AfterValueChangedDirective implements OnDestroy {
@Output()
public afterValueChanged: EventEmitter<any> = new EventEmitter<any>();
@Input()
public valueChangeDelay = 300;
private stream: Subject<any> = new Subject<any>();
private subscription: Subscription;
constructor() {
this.subscription = this.stream
.pipe(debounceTime(this.valueChangeDelay))
.subscribe((value: any) => this.afterValueChanged.next(value));
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
@HostListener('valueChange', [ '$event' ])
public onValueChange(value: any): void {
this.stream.next(value);
}
}
用法
<kendo-numerictextbox
(afterValueChanged)="onAfterValueChange($event)"
(valueChange)="onValueChange($event)">
</kendo-numerictextbox>
public onAfterValueChange(value: number): void {
this.value = value;
}