如何使用rxjs在angular2中对输入keyup事件实现去抖服务 [英] How to achieve a debounce service on input keyup event in angular2 with rxjs

查看:814
本文介绍了如何使用rxjs在angular2中对输入keyup事件实现去抖服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过输入加密事件调用服务。

I am trying to call to a service on input key-up event.

HTML

<input placeholder="enter name" (keyup)='onKeyUp($event)'>

以下是 onKeyUp()函数

onKeyUp(event) {
    let observable = Observable.fromEvent(event.target, 'keyup')
        .map(value => event.target.value)
        .debounceTime(1000)
        .distinctUntilChanged()
        .flatMap((search) => {
            // call the service
        });
    observable.subscribe((data) => {
        // data
    });
}

从浏览器的网络标签中发现,它正在调用每次按键事件的按键功能(正如它应该做的那样),但我想要达到的是每次服务呼叫之间1秒的去抖时间。此外,如果我移动箭头键移动,则会触发事件。

It was found from the network tab of the browser that, it is calling the key-up function on every key-up event(as it is supposed to do), but what I am trying to achieve is a debounce time of 1sec between each service call. Also, the event is triggered if I move the arrow key move.

plunkr link

推荐答案

所以这个链是非常正确的,但问题是你要创建一个Observable并在每个<$ c $上订阅它c> keyup 事件。这就是它多次打印相同值的原因。只有多个订阅并不是您想要做的。

So the chain is really correct but the problem is that you're creating an Observable and subscribe to it on every keyup event. That's why it prints the same value multiple times. There're simply multiple subscriptions which is not what you want to do.

显然有更多方法可以正确完成,例如:

There're obviously more ways to do it correctly, for example:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="text" (keyup)='keyUp.next($event)'>
    </div>
  `,
})
export class App implements OnDestroy {

  public keyUp = new Subject<KeyboardEvent>();

  private subscription: Subscription;

  constructor() {
    this.subscription = this.keyUp.pipe(
      map(event => event.target.value),
      debounceTime(1000),
      distinctUntilChanged(),
      mergeMap(search => of(search).pipe(
        delay(500),
      )),
    ).subscribe(console.log);
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }
}

查看更新的演示: http://plnkr.co/edit/mAMlgycTcvrYf7509DOP

2019年1月:更新了RxJS 6

Jan 2019: Updated for RxJS 6

这篇关于如何使用rxjs在angular2中对输入keyup事件实现去抖服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆