如何实现搜索键向上的去抖时间

Pra*_*ale 3 debouncing typescript angular

我正在我的应用程序中实现搜索功能,我想在按键时实现去抖时间。谁能帮我解决这个问题吗

超文本标记语言

<div class="mt-4">
    <div class="form-group has-search">
      <span class="fa fa-search form-control-feedback"></span>
      <input type="search" class="form-control" [(ngModel)]="searchKeywords" (keyup)="getSmartSearchValues(searchKeywords)" (search)="clearSearch()" placeholder="Search here">
    </div>
  </div>
Run Code Online (Sandbox Code Playgroud)

我已经尝试过这个,但它显示错误

  searchTextChanged = new Subject<string>();

ngOnInit(): void {
    this.subscription = this.searchTextChanged
    .debounceTime(1000)
    .distinctUntilChanged()
    .mergeMap(search => this.getSmartSearchValues('', ''))
    .subscribe(() => { });
    this.getAllData();
    if (this.CoffeeItemList.length === 0) {
      this.empty = true;
    }
    this.getItemsCount('');
  }
Run Code Online (Sandbox Code Playgroud)

错误

Property 'debounceTime' does not exist on type 'Subject<string>'.
Property 'subscription' does not exist on type 'AppComponent'
Run Code Online (Sandbox Code Playgroud)

zer*_*ewl 5

您可以将 a 添加debounceTime到您的 FormControl.

例如:

...
Component({
  selector: 'my-app',
  template: `<input type=text [value]="firstName" [formControl]="firstNameControl">
    <br>{{firstName}}`
})
export class AppComponent {
  firstName        = 'Name';
  firstNameControl = new FormControl();
  formCtrlSub: Subscription;
  ngOnInit() {
    // debounce keystroke events
    this.formCtrlSub = this.firstNameControl.valueChanges
      .debounceTime(1000)
      .subscribe(newValue => this.firstName = newValue);
...
Run Code Online (Sandbox Code Playgroud)

或者你可以使用fromEvent

export class HelloComponent implements OnInit, OnDestroy {
  @Input() name: string;
  @ViewChild("editor") editor: ElementRef;
  subscription: Subscription;

  ngOnInit() {
    this.subscription = fromEvent(this.editor.nativeElement, "keyup").pipe(
      map(event => this.editor.nativeElement.value),
      debounceTime(1000)
    ).subscribe(val => this.name = val);
  }
Run Code Online (Sandbox Code Playgroud)
<form>
  <input type="text" #editor name="hello">
</form>
Run Code Online (Sandbox Code Playgroud)

参见附件Stackblitz

或者将您绑定ngModelChange到 Observable 并debounceTime与它一起使用:

<hello name="{{ name }}"></hello>
<input class="form-control" [(ngModel)]="userQuestion" 
type="text" name="userQuestion" id="userQuestions"
(ngModelChange)="this.userQuestionUpdate.next($event)">

<ul>
  <li *ngFor="let message of consoleMessages">{{message}}</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
export class AppComponent {
  name = 'Angular 6';
  public consoleMessages: string[] = [];
  public userQuestion: string;
  userQuestionUpdate = new Subject<string>();

  constructor() {
    // Debounce search.
    this.userQuestionUpdate.pipe(
      debounceTime(400),
      distinctUntilChanged())
      .subscribe(value => {
        this.consoleMessages.push(value);
      });
  }
}
Run Code Online (Sandbox Code Playgroud)

参见Stackblitz2

编辑:

另外,您可以在 Angular 的官方文档中找到有关实用可观察用法(在哪里debounceTime使用)的示例。

import { fromEvent } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { debounceTime, distinctUntilChanged, filter, map, switchMap } from 'rxjs/operators';


const searchBox = document.getElementById('search-box');

const typeahead = fromEvent(searchBox, 'input').pipe(
  map((e: KeyboardEvent) => (e.target as HTMLInputElement).value),
  filter(text => text.length > 2),
  debounceTime(10),
  distinctUntilChanged(),
  switchMap(() => ajax('/api/endpoint'))
);

typeahead.subscribe(data => {
 // Handle the data from the API
});
Run Code Online (Sandbox Code Playgroud)