Angular 在表单的 ValueChanges 中去抖动
Angular Debounce within ValueChanges of form
我有一个名为 filteredUserNames 的列表,其中包含很多用户。每次我更改表单上的值时,它都会启动一个新的数据过滤器。我知道要延迟时间以便不是每个角色都会触发我需要使用去抖动的新过滤器,但我不确定在哪里添加它。它应该在价值变化订阅中吗?还有什么是正确的实施方式?
我有
searchString = new BehaviorSubject("");
searchString$ = this.searchString.asObservable();
在构造函数中
this.myForm = this.fb.group({
searchString: [""],
});
this.myForm.controls.searchString.valueChanges.subscribe((val) => {
// SHOULD THE DEBOUNCE GO HERE ?? //
this.searchString.next(val);
}
在 ngOnInit
this.searchString$.subscribe((searchTerm) => {
console.log(this.userNames);
if (this.userNames !== undefined) {
this.filteredUserNames = this.userNames.filter(
(userName) =>
userName.searchTerms
.toLowerCase()
.indexOf(searchTerm.toLowerCase()) !== -1
);
};
});
试试这个,你可以添加 distinctUntilChanged 来忽略相似的值,并添加 tap 运算符来处理你的副作用,在你的情况下会发出一个您的 bahviorSubject
的新价值
import { tap, distinctUntilChanged, debounceTime} from 'rxjs/operators';
...
this.myForm.controls.searchString.valueChanges.pipe(
debounceTime(400),
distinctUntilChanged(),
tap((val) => this.searchString.next(val))
).subscribe()
我有一个名为 filteredUserNames 的列表,其中包含很多用户。每次我更改表单上的值时,它都会启动一个新的数据过滤器。我知道要延迟时间以便不是每个角色都会触发我需要使用去抖动的新过滤器,但我不确定在哪里添加它。它应该在价值变化订阅中吗?还有什么是正确的实施方式?
我有
searchString = new BehaviorSubject("");
searchString$ = this.searchString.asObservable();
在构造函数中
this.myForm = this.fb.group({
searchString: [""],
});
this.myForm.controls.searchString.valueChanges.subscribe((val) => {
// SHOULD THE DEBOUNCE GO HERE ?? //
this.searchString.next(val);
}
在 ngOnInit
this.searchString$.subscribe((searchTerm) => {
console.log(this.userNames);
if (this.userNames !== undefined) {
this.filteredUserNames = this.userNames.filter(
(userName) =>
userName.searchTerms
.toLowerCase()
.indexOf(searchTerm.toLowerCase()) !== -1
);
};
});
试试这个,你可以添加 distinctUntilChanged 来忽略相似的值,并添加 tap 运算符来处理你的副作用,在你的情况下会发出一个您的 bahviorSubject
的新价值import { tap, distinctUntilChanged, debounceTime} from 'rxjs/operators';
...
this.myForm.controls.searchString.valueChanges.pipe(
debounceTime(400),
distinctUntilChanged(),
tap((val) => this.searchString.next(val))
).subscribe()