首页 > 解决方案 > 如何修复 'debounceTime & distinctUntilChanged | Angular 5 中使用打字稿的 RxJS 错误

问题描述

我有一个输入搜索元素,我检测到 keyup,我想使用 debounce 来限制对 API 的请求,但我无法让它工作。我只是想测试 debounceTime 和 distinctUntilChanged。

我已经尝试过(Keyup)但无法正常工作。

<input (keyup)="onKeyUp($event)"  id="testInput" autocomplete="off" type="text" name="searchFilterText" class="m-list-search__form-input" value="" placeholder="Search...">

这是打字稿文件中的代码。

searchInput = document.getElementById('testInput');
observable: any;

/// <summary>
/// Process the search term provided on key up for the input field.
/// </summary>
/// <param name="searchTerm">The search term.</param>
onKeyUp(event: KeyboardEvent) {
    //console.log(event);
    let element = event.target as HTMLInputElement;
    let value = element.value;

    this.observable = fromEvent(this.searchInput, event.type)
        .debounceTime(500) // millisecs until value gets emitted.
        .distinctUntilChanged()
        .subscribe(function (event) {
            console.log(event.target.value);
        });
}

预期结果是控制台日志中使用 debounceTime 和 distinctUntilChanged 的​​延迟搜索结果值。

标签: angulartypescript

解决方案


你可以试试这个:

模板

<input  
       id="testInput" autocomplete="off"
       type="text" #searchText
       name="searchFilterText" class="m-list-search__form-input"
       value=""
       placeholder="Search...">

注意模板引用变量:#searchText. 这允许在不需要的情况下访问输入元素getElementById(通常不建议在 Angular 应用程序中使用)。

零件

import { Component, AfterViewInit, ViewChild } from '@angular/core';
import { fromEvent } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

@Component({
   templateUrl: './search.component.html'
})
export class SearchComponent implements AfterViewInit {
  @ViewChild('searchText') searchTextRef;

  ngAfterViewInit() {
    if (this.searchTextRef) {
      fromEvent(this.searchTextRef.nativeElement, 'keyup')
        .pipe(
            debounceTime(500),
            distinctUntilChanged()
        ).subscribe(
          value => console.log(this.searchTextRef.nativeElement.value)
        )
    }
  }
}

此代码用于@ViewChild获取对标有#searchText模板引用变量的元素的引用。

然后它使用类似于您为debounceTime.

我在这里有一个堆栈闪电战: https ://stackblitz.com/edit/angular-debounce-deborahk

你可以在这里找到更多信息: Observable.fromEvent - RXJS

注意:如果您使用响应式表单,这会更容易,因为您可以直接访问valueChanges表单上任何输入元素的 observable。

反应形式

模板

<input  
       id="testInput"
       [formControl]="search"
       autocomplete="off"
       type="text"
       class="m-list-search__form-input"
       value=""
       placeholder="Search...">

注意formControl指令。

零件

  // For reactive forms
  search = new FormControl();

  ngOnInit() {
    this.search.valueChanges
            .pipe(
          debounceTime(500),
          distinctUntilChanged()
        ).subscribe(
          value => console.log("Reactive Forms implementation: " + value)
        )
  }

推荐阅读