【问题标题】:How to create an Observable of type boolean?如何创建布尔类型的 Observable?
【发布时间】:2019-03-12 23:02:18
【问题描述】:

我需要创建一个 Observable,它发出一个布尔值并且可以从一个函数中更改。

我试过了

showModal$ = new Observable<boolean>();

但它不起作用。

我需要的是showModal$ 默认为false。并用函数改变它的值

change() {
  this.showModal$ = !this.showModal$;
}

我正在使用 Angular2,我想从不同的组件订阅该 Observable。

最好的方法是什么?

【问题讨论】:

    标签: javascript angular typescript rxjs observable


    【解决方案1】:

    使用 BehaviorSubject

    showModal$ = new BehaviorSubject<boolean>(false);
    
    change() {
      this.showModal$.next(!this.showModal$.getValue());
    }
    

    这是一个 JavaScript 演示

    const { BehaviorSubject, fromEvent } = rxjs;
    
    const showModal$ = new BehaviorSubject(false);
    
    function change() {
      showModal$.next(!showModal$.getValue());
    }
    
    fromEvent(document.getElementById('change'), 'click').subscribe(_ => {
      change();
    });
    
    showModal$.subscribe(showModal => {
      console.log(`Modal is shown is ${showModal}`);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>
    <button id="change">Change</button>

    【讨论】:

      猜你喜欢
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      • 2010-09-25
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多