【问题标题】:Debouncing based on $event基于 $event 去抖动
【发布时间】:2017-12-20 16:58:53
【问题描述】:

我有兴趣在 angular5 中使用 rxjs5 来消除输入抖动,但使用来自 keyup$event,而不是使用 valueChanged 并将其硬分配给组件(似乎是例子太多了)。

在下面的示例中,假设我想使用locsearchTerm 进行进一步处理;

querySearchTerm(event){
  let searchTerm : Observable<string> = event.target.value;
  let locsearchTerm  =  searchTerm
                          .distinctUntilChanged()
                          .debounceTime(4000)
                          //... etc, etc
}

尽管我在模板输入元素中绑定到(keyup)=querySearchTerm(event),并将searchTerm 分配为可观察字符串,但返回错误searchTerm.distinctUntilChanged is not a function

有人可以解释为什么这样的事情不起作用,如果可能的话,提供解决方案吗?

【问题讨论】:

    标签: rxjs5 angular5


    【解决方案1】:

    你不能通过编写将字符串转换为 Observable

    const obs$: Observable<string> = "Hello";
    

    type 只是 Typescript 的类型信息,不带任何逻辑。因此,该分配不会神奇地将您的事件变成流(此外,在这种情况下,单个事件的流有什么好处?)

    您需要从事件流中创建一个 Observable,将所有事件捕获到同一个流中:

    // We use a subject to capture the events because a
    // subject is both an observer and an observable, which
    // means we can both subscribe to it and emit to it. 
    private events$ = new Subject();
    
    // Here you can subscribe to your observable and
    // manipulate the stream. 
    constructor() {
        this.events$
            .debounceTime(1000)
            .subscribe(event => console.log(event));
    } 
    
    // When we receive an event, just emit it on the subject.
    // The subscription handles the rest. 
    querySearchTerm(event) { 
        events$.next(event); 
    }
    

    如果你有对 DOM 元素的引用,你也可以使用

    const events$ = Observable.fromEvent(input, "keyup");
    

    创建 observable 而不是手动创建。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-13
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-24
      • 2015-06-28
      • 1970-01-01
      相关资源
      最近更新 更多