Как реализовать время отката при поиске ключа вверх - PullRequest
3 голосов
/ 12 марта 2020

Я использую в своем приложении функцию поиска, которую я хотел использовать для определения времени отката при включении ключа. Может ли кто-нибудь, пожалуйста, помогите мне с этим

HTML

<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>

у меня пытается это, но он показывает ошибку

  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('');
  }

Ошибки

Property 'debounceTime' does not exist on type 'Subject<string>'.
Property 'subscription' does not exist on type 'AppComponent'

Ответы [ 2 ]

3 голосов
/ 12 марта 2020

Вы можете добавить 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);
...

или вы можете использовать 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);
  }
<form>
  <input type="text" #editor name="hello">
</form>

См. Прикрепленный Stackblitz

или вы связываете ngModelChange с наблюдаемой и используете 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>
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);
      });
  }
}

См. 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
});
2 голосов
/ 12 марта 2020

Вы ищете что-то подобное? Смотрите эту ссылку

export class AppComponent implements OnInit {

  @ViewChild('searchKeywords') searchKeywords: ElementRef;

  constructor(private httpClient: HttpClient) {}

  ngOnInit() {
    fromEvent(this.searchKeywords.nativeElement, 'keyup').pipe(
      // get value
      map((event: any) => event.target.value)
      // if character length greater then 2
      ,filter(res => res.length > 2)
      // Time in milliseconds between key events
      ,debounceTime(500)        
      // If previous query is diffent from current   
      ,distinctUntilChanged()
      ,switchMapTo(this.http.get<any>('...'))
      // subscription for response
      ).subscribe(res => {
        console.log(res);
      });
  }
}
...