angular - 如何修复 '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 的延迟搜索结果值。
解决方案
你可以试试这个:
模板
<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)
)
}
推荐阅读
- macos - 无法使用 smartbear 代码协作者的 P4 插件添加文件以供审阅
- python - 熊猫数据框中的正则表达式
- php - Cookie 和字符串比较不匹配
- python-3.x - AWS Lambda Python - 将密钥复制到“文件夹”会创建嵌套的“文件夹”。如何从监视中排除“文件夹”
- f# - 无法为 Orleans 3.0 生成 F# 接口库
- java - 在 Hybris-Spartacus 项目中具有新扩展的自定义 commercewebservices
- r - 使用 purrr::map 重命名更大列表中列表中元素的行名?
- sql - 将所有记录放在一个表中的性能损失
- html - 在 Chrome 中禁用 HTML 自动修复
- sql - ROW_NUMBER() OVER 因大型查询而超时。最佳解决方案?