Директива Debounce для отображения результатов поиска
У меня есть директива для поиска элементов по заголовку, теперь я пытаюсь понять, как сделать директиву для задержки, чтобы при вводе текста в поле ввода, результаты отображались через 500 мс.
Мой debounce.directive.ts
@Directive({
selector: '[appDebounce]',
})
export class DebounceDirective implements OnInit, OnDestroy {
@Output() debounceKeyUp = new EventEmitter();
private keyup = new Subject();
private subscription: Subscription;
constructor() {}
ngOnInit() {
this.subscription = this.keyup
.pipe(debounceTime(500))
.subscribe((e) => this.debounceKeyUp.emit(e));
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
@HostListener('keyup', ['$event'])
keyEvent(event: KeyboardEvent) {
console.log(event);
this.keyup.next(event);
}
}
Мой search.component.html
<div class="search-component">
<input appDebounce class="search-box" placeholder="Todo search" [formControl]="searchValue" />
</div>
Мой search.component.ts
В этом файле у меня есть метод debounceTime в ngOnInit, но мне нужно избавиться от него в пользу директивы
@Component({
selector: 'app-search-task',
templateUrl: './search-task.component.html',
styleUrls: ['./search-task.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SearchTaskComponent implements OnInit {
private searchTerms$ = new Subject<string>();
private ngUnsubscribe$ = new Subject<void>();
searchValue = new FormControl();
constructor(
private todoService: TodoService,
private changeDetectorRef: ChangeDetectorRef
) {}
ngOnInit(): void {
this.searchTerms$
.pipe(
takeUntil(this.ngUnsubscribe$),
debounceTime(300),
distinctUntilChanged()
)
.subscribe((term) => {
this.todoService.setSearchTerm(term);
this.changeDetectorRef.markForCheck();
});
this.searchValue.valueChanges.subscribe((value) => {
this.searchTerms$.next(value);
});
this.searchValue.setValue('');
}
onDestroy() {
this.ngUnsubscribe$.next();
this.ngUnsubscribe$.complete();
}
}
Но если это не работает, как мне это решить?