RxJs动态debounceTime不是动态的

时间:2019-08-01 08:57:39

标签: angular rxjs

我创建了一个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);
    }
}

问题在于searchFieldValueOutputDelay仅是第一次使用,因此它的值为400,而不是我在输入中提供的值。

<input (searchValueUpdated)="searchCard($event)" [searchFieldValueOutputDelay]="1000" type="search">

1 个答案:

答案 0 :(得分:1)

debounceTime的值仅在可观察的创建时间上评估一次。

要能够动态更新debounceTime,请将debouncetimer一起使用,如下所示:

@Output() searchValueUpdated = this._inputObservable$.asObservable().pipe(
        debounce(()=>timer(this.searchFieldValueOutputDelay)),
        distinctUntilChanged(),
        tap(() => console.log('emit', this.searchFieldValueOutputDelay))
    );