为什么rxjs debounceTime在使用'of'运算符创建的可观测对象上不起作用? [英] Why rxjs debounceTime does not work on observables created using 'of' operator?
问题描述
使用角7
和 rxjs 6
:
<input (input)="onChange($event.target.value)">
为什么以下内容不会反跳?
onChange(val: string) {
of(val)
.pipe(
debounceTime(300)
).subscribe(valx => {
console.log(valx);
});
}
但是这样做:
searchTerm$: Subject<string> = new Subject();
this.searchTerm$.pipe(
debounceTime(300),
).subscribe(val => {
console.log(val);
});
onChange(val: string) {
this.searchTerm$.next(val);
}
推荐答案
这不是因为 of()
。在第一个示例中,每次调用 onChange($ event.target.value)
时,您将使用自己的 debounceTime $创建一个新链。 c $ c>,它是自己的计时器。因此,它永远不会反跳,因为每个输入更改都有其自己的链。
This isn't because of of()
. In your first example every time you call onChange($event.target.value)
you're creating a new chain with it's own debounceTime
and it's own timer. So it never debounces anything because every input change has its own chain.
但是,如果您使用Subject(例如第二个示例)并将所有事件通过 this.searchTerm $ .next(val)
,那么您只有一个链,每个事件都在顶部推送,然后按预期的方式反跳。
However, if you use Subject (like in your second example) and push all events through this.searchTerm$.next(val)
then you have just one chain where each event is push at the top and then debounced as you expect.
这篇关于为什么rxjs debounceTime在使用'of'运算符创建的可观测对象上不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!