简体   繁体   English

如何在BehaviorSubject上链接订阅 <boolean> ?

[英]How to chain subscription on BehaviorSubject<boolean>?

I have an Angular app which shows and hides an input field depending on the contents of another input field. 我有一个Angular应用,它根据另一个输入字段的内容显示和隐藏一个输入字段。 Now I need to do some auto formatations on the second field when the user types something into it. 现在,当用户在第二个字段中输入内容时,我需要对其进行一些自动格式化。 But the field is hidden when the component loads, so I need to check the values of the first field to check if the second should be shown and then, when it is visible subscribe to its valueChanges. 但是在组件加载时该字段是隐藏的,因此我需要检查第一个字段的值以检查是否应显示第二个字段,然后在可见时订阅其valueChanges。

My code looks like this: 我的代码如下所示:

export class MyInputComponent implements AfterViewInit {
  private subscription = Subscription.EMPTY;

  @ViewChild('firstInput', { read: NgControl }}
  public firstInput: NgControl;

  @ViewChild('secondInput', { read: NgControl }}
  public secondInput: NgControl;

  public isSecondInputVisible = new BehaviorSubject<boolean>(false);

  public ngAfterViewInit() {
    this.firstInput.valuesChanges!.subscribe((first) => {
      this.isSecondInputVisible.next(first.length > 4);
    });

    this.isSecondInputVisible.subscribe((isVisible) => {
      if (isVisible) {
        this.subscription = this.secondInput.valueChanges!.subscribe((value) => {
          // do something...
        });
      } else {
        this.subscription.unsubscribe();
      }
    });
  }
}

I was wondering if there is a way to chain the subscriptions, I won't have too much indentation and nesting in the code. 我想知道是否有一种链接订阅的方法,我在代码中不会有太多的缩进和嵌套。 I thought this may be possible using pipe but I have not yet found a way. 我认为使用管道可以实现此目的,但我尚未找到方法。

Is there a way to optimize the subscription part? 有没有一种方法可以优化订阅部分?

You can use concatMap and inside it return empty() in case the field is invisible. 您可以使用concatMap并在其中将返回empty() ,以防字段不可见。

this.isSecondInputVisible
  .pipe(
    concatMap(isVisible => isVisible
      ? this.secondInput.valueChanges!
      : empty()
    )
  )
  .subscribe(valueChanged => /* do something...*/)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM