【问题标题】:How to get last event from the `fromEvent` method如何从`fromEvent`方法获取最后一个事件
【发布时间】:2021-11-30 20:46:08
【问题描述】:

我正在尝试使用 rxjs 捕捉来自 keyup 的最后一个事件,但一直在获取一堆控制台。

这是我的角度指令:

import { Directive, AfterContentChecked, ElementRef, HostListener } from '@angular/core';
import { fromEvent, merge, Observable } from 'rxjs';
import { distinctUntilChanged, debounceTime, last, map } from 'rxjs/operators';

@Directive({
  selector: '[appFocuser]'
})
export class FocuserDirective implements AfterContentChecked {
  focusableArray = [];
  parent = null;
  count = 0;
  currentFocus: HTMLElement;
  constructor(private el: ElementRef) {}

  ngAfterContentChecked() {
    this.parent = this.el.nativeElement;
    this.focusableArray = Array.from(this.parent.querySelectorAll(`[data-focus=true]`));
    this.currentFocus = this.focusableArray[0] as HTMLElement;
    if (this.currentFocus) {
      this.currentFocus.focus();
      this.count++;
    }

    this.eventHandler();
  }

  eventHandler() {
    const events = fromEvent(this.parent, 'keyup')
      .pipe(debounceTime(100))
      .pipe(distinctUntilChanged());
    events.pipe().subscribe(console.log); //each time consoles 7,8
  }
  //
}

处理这个问题的正确方法是什么?

Live Demo

【问题讨论】:

    标签: angular rxjs angular-directive rxjs-pipeable-operators


    【解决方案1】:

    如果你只想要最后一个事件,你可以试试最后一个运算符:

    eventHandler() {
        const events = fromEvent(this.parent, 'keyup')
          .pipe(
           debounceTime(100),
           distinctUntilChanged(),
           last());
    
        events.pipe().subscribe(console.log);
      }
    

    如果你想参加最后 2 个活动,你可以试试这个:

    eventHandler() {
        const events = fromEvent(this.parent, 'keyup')
          .pipe(
           debounceTime(100),
           distinctUntilChanged(),
           takeLast(2));
    
        events.pipe().subscribe(console.log);
      }
    

    【讨论】:

    • 我认为 last 和 takeLast 仅在 observable 完成时才起作用,而 fromEvent Observable 永远不会发生这种情况
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多