【问题标题】:Custom distinctUntilChanged implementation自定义 distinctUntilChanged 实现
【发布时间】:2021-12-21 15:58:20
【问题描述】:

在我们的 Angular 应用程序中,我们经常使用 distinctUntilChanged() 并且我们想要使用它直接比较 form.valueChanges。如本问题所述:https://stackoverflow.com/a/53825991/1003686form.valueChanges 上使用 distinctUntilChanged 将无法正常工作:

this.myFormControl.valueChanges
  .pipe(distinctUntilChanged())
  .subscribe(newValue => {
    console.log('fires endlessly');
  });

相反,我必须这样写才能进行非常基本的比较。

this.searchAndFilterForm.valueChanges
  .pipe(distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b))
  .subscribe(newValue => {
    console.log('fires only on real changes');
  });

我不想在每个表单 valuechange 上定义自定义比较,而是希望有一个名为 formDistinctUntilChanged() 的新管道运算符,我可以在需要时使用和重构。

我看到distinctUntilChanged()MonoTypeOperatorFunction。如何实现自定义 MonoTypeOperatorFunction 以便获得 formDistinctUntilChanged() 运算符?最好只使用带有预定义比较的普通 distinctUntilChanged()

基本上,我正在寻找与普通 distinctUntil 相同但具有预定义比较的东西,我可以在多个组件中重复使用。

this.myFormControl.valueChanges
  .pipe(formDistinctUntilChanged())
  .subscribe(newValue => {
    console.log('fires only on real changes');
  });

创建像https://tane.dev/2021/01/creating-custom-rxjs-operators/ 中描述的自定义 rxjs 运算符在我的 Angular 环境中并不能真正工作,因为我们定义了 eslint(prefer-arrow/prefer-arrow-functions) 并且我不完全理解如何使用另一个MonoTypeOperatorFunctionMonoTypeOperatorFunction 中。

【问题讨论】:

    标签: angular rxjs-pipeable-operators


    【解决方案1】:

    pipeable 操作符只是一个接受 observable 并返回 observable 的函数。所以你可以使用这样的东西:

    const formDistinctUntilChanged =
      <T>() =>
      (obs$: Observable<T>): Observable<T> =>
        obs$.pipe(distinctUntilChanged(/*your comparator*/));
    

    【讨论】:

    • 这正是我想要的。就我而言,我必须导出该功能。谢谢。
    猜你喜欢
    • 2014-02-01
    • 2014-10-14
    • 2011-06-04
    • 2010-10-29
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多