rxjs distinctUntilChanged比较input框的两次值是否相同

业务场景:一个input框,监听当前内容发生变化,判断非空、前后两次值不一样,防抖后,发送请求并展示数据

使用of创建一个流,使用该操作符

of<Person>(
      { age: 4, name: 'Foo' },
      { age: 7, name: 'Bar' },
      { age: 5, name: 'Foo' },
      { age: 6, name: 'Foo' },
      { age: 8, name: 'Foo' },
      { age: 9, name: 'Foo' },
      { age: 2, name: 'Foo1' },
    )
      .pipe(
        distinctUntilChanged((p, q) => {
          console.log(p, q, p.name === q.name);
          return p.name === q.name;
        })
      )
      .subscribe((x) => console.log(x));
      //{"age":4,"name":"Foo"}
      //{"age":7,"name":"Bar"}
      //{"age":5,"name":"Foo"}
      //{"age":2,"name":"Foo1"}

监听input的变化

    this.input$ = fromEvent(this.inputEl.nativeElement, 'input');
    this.input$
      .pipe(
        filter((el) => {
          return Boolean(el.target.value);
        }),
        // map(input => input),
        distinctUntilChanged((pre: InputEvent, next: InputEvent) => {
          return (
            (pre.target as HTMLInputElement).value ===
            (next.target as HTMLInputElement).value
          );
        }),
        debounceTime(500)
      )
      .subscribe((val) => {
        console.log(val)
      });

期望使用rxjs操作符,能比较两次值的,并且保留input事件触发(不使用change事件),如果一致则不做操作(不要手动缓存比)

阅读 2.9k
1 个回答
watchInput() {
    this.input$ = fromEvent(this.inputEl.nativeElement, 'input');
    this.input$
      .pipe(
        filter((el) => {
          return Boolean(el.target.value);
        }), // 过滤空值
        map((e) => e.target.value), // 映射value
        distinctUntilChanged((pre, cur) => pre === cur), // 校验前后两次的value是否一致
        debounceTime(500),
        switchMap((val) => {
          if (this.cache.get(val)) {
            return this.cache.get(val);
          }
          return this.http.get('http://localhost:8000/list').pipe(
            tap((result) => this.cache.set(val, of(result))),
            shareReplay(1)
          );
        }) // 取消上一次未完成的流
      )
      .subscribe((res) => {
        this.list = res as IInputResponse[];
        this.cdr.markForCheck();
      });
  }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进