我创建了一个 Angular 指令,该指令应用于输入并以一些延迟(用于搜索)发出其值。
这个代码如下
@Directive({
selector: '[search-field]'
})
export class SearchFieldDirective {
@Input() searchFieldValueOutputDelay = 400;
private _inputObservable$ = new Subject();
@Output() searchValueUpdated = this._inputObservable$.asObservable().pipe(
debounceTime(this.searchFieldValueOutputDelay),
distinctUntilChanged(),
tap(() => console.log('emit', this.searchFieldValueOutputDelay))
);
@HostListener('keyup', ['$event.target.value'])
onChange(e) {
console.log("change");
this._inputObservable$.next(e);
}
}
Run Code Online (Sandbox Code Playgroud)
问题是searchFieldValueOutputDelay它只在第一次使用,因此它的值为 400 而不是我在输入时提供的值。
<input (searchValueUpdated)="searchCard($event)" [searchFieldValueOutputDelay]="1000" type="search">
debounceTime 的值仅在可观察的创建时间评估一次。
为了能够动态更新 debounceTime,将debounce与timer一起使用,如下所示:
@Output() searchValueUpdated = this._inputObservable$.asObservable().pipe(
debounce(()=>timer(this.searchFieldValueOutputDelay)),
distinctUntilChanged(),
tap(() => console.log('emit', this.searchFieldValueOutputDelay))
);
Run Code Online (Sandbox Code Playgroud)