在 Angualr 和 RxJS 中,在表单更改后立即执行某些操作的正确方法是什么?

What is the correct way to do something immediately after a form changed and also with a delay in Angualr and RxJS?

我在组件中有一个表单,当它的值改变时应该做两件事:

父组件中的一项服务将在表单值更改时向 API 发送新请求。这不应在每次击键时发生,以减少请求。所以我限制了发出事件。

不幸的是,我现在有两个订阅者:一个处理视图更新,另一个 debounceTime 处理 EventEmitter:

private subscribeToChanges(): void {
  this.form.valueChanges.pipe(
    distinctUntilChanged(),
    takeUntil(this.isDestroyed$)
  ).subscribe(() => {
    this.updateView();
  });

  this.form.valueChanges.pipe(
    debounceTime(400),
    distinctUntilChanged(),
    takeUntil(this.isDestroyed$)
  ).subscribe(() => {
    this.changed.emit(this.form.value);
  });
}

我可以自己在第一个订阅者中添加超时,但这也不太好。

正确的做法是什么?

您可以尝试使用 tap 运算符并在点击后应用 debounceTime。尝试以下

private subscribeToChanges(): void {
  this.form.valueChanges.pipe(
    distinctUntilChanged(),
    takeUntil(this.isDestroyed$),
    tap(value => this.updateView()),
    debounceTime(400)
  ).subscribe(() => {
    this.changed.emit(this.form.value);
  });
}

我认为没有办法是客观的 "correct" 除非它不起作用。这是另一种方式。

private subscribeToChanges(): void {
  const subscription = this.form.valueChanges.pipe(
    distinctUntilChanged(),
    takeUntil(this.isDestroyed$)
  );

  subscription.subscribe(() => {
    this.updateView();
  });

  subscription.pipe(
    debounceTime(400),
  ).subscribe(() => {
    this.changed.emit(this.form.value);
  });
}