我正在使用 Rxjs 6,它根据表单字段中的 (keyup) 事件过滤 Firebase 返回的可观察值。
当用户在表单字段中没有值的情况下不断按退格键时,我遇到一个问题,然后看起来可观察对象不断刷新。
使用 DistinctUntilChanged() 添加管道似乎没有效果:
打字稿过滤功能:
updateFilter2() {
const val = this.filteredValue.toLowerCase().toString().trim();
if (this.filteredValue) {
this.loadingIndicator = true;
this.rows = this.svc.getData()
.pipe(
distinctUntilChanged(),
debounceTime(300),
map(_co => _co.filter(_company =>
_company['company'].toLowerCase().trim().indexOf(val) !== -1 || !val
||
_company['name'].toLowerCase().trim().indexOf(val) !== -1 || !val
||
_company['gender'].toLowerCase().trim().indexOf(val) !== -1 || !val
)),
tap(res => {
this.loadingIndicator = false;
})
);
}
else {
this.rows = this.svc.getData()
.pipe(distinctUntilChanged())
this.loadingIndicator = false;
}
this.table.offset = 0;
}
HTML 模板:
<mat-form-field style="padding:8px;">
<input
type='text'
matInput
[(ngModel)] = "filteredValue"
style='padding:8px;margin:15px auto;width:30%;'
placeholder='Type to filter the name column...'
(input)='updateFilter2()'
/>
</mat-form-field>
我有一个 Stackblitz 重现了这种行为:https://stackblitz.com/edit/angular-nyqcuk
还有其他方法可以解决吗?
Thanks
问题是总是使用 getData。您首先查看更改,然后切换映射以获取数据。所以你必须有一个可观察的变化。使用“FormControl”,而不是带有 [(ngModel)] 的输入
所以,在你的 .html 中
<input type="text" [formControl]="search">
代码必须是
search= new FormControl(); //Declare the formControl
constructor() {}
ngOnInit() {
this.search.valueChanges.pipe(
debounceTime(400),
distinctUntilChanged(),
tap((term)=>{
//here the value has changed
this.loadingIndicator = true;
}),
switchMap(filteredValue=> {
//We not return the value changed,
return this.svc.getData().pipe(
map(_co => {
return _co.filter(...)
}),
tap(()=>{
this.loadingIndicator=false;
}))
})).subscribe(result=>{
this.result=result
})
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)