[英]Type 'Observable<boolean | “”>' is not assignable to type 'Observable<boolean>' TS2322
[英]How to create an Observable of type boolean?
我需要创建一个Observable,它发出一个booleand并且可以从函数中更改。
我试过了
showModal$ = new Observable<boolean>();
但这行不通。
我需要的是showModal$
默认为false
。 并通过功能更改其值
change() {
this.showModal$ = !this.showModal$;
}
我正在使用Angular2,我想从differents组件订阅该Observable。
最好的方法是什么?
使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.