[英]BehaviorSubject with boolean value is not working as intended
我實現了一個簡單的BehaviorSubject
,
import {BehaviorSubject} from "rxjs";
class MyWeirdoClass {
constructor() {}
private st: Subject<boolean> = new BehaviorSubject<boolean>(null);
changeSt(val:boolean){
this.st.next(val);
}
val(){
this.st.subscribe(res=>{
if (res){
console.log(res);
}
})
}
stStatus() {
this.val();
this.changeSt(true);
this.val();
this.changeSt(false);
this.val();
}
}
現在運行stStatus()
會在控制台上顯示以下輸出。
true
true
雖然我期待價值
false
true
false
我的實施有什么問題?
你得到的輸出是正確的:
this.val();
由於if (res) {...}
這只會使第一個訂閱無法打印任何內容。
this.changeSt(true);
將值設置為true
,由第一個訂閱打印。
this.val();
使第二個訂閱打印第二個true
。
this.changeSt(false);
您將其設置為false
,由於if (res) {...}
而被所有訂閱者忽略。
this.val();
與上述相同。
因為這些線:
if (res){
console.log(res);
}
只有當它真實時才會記錄該值。
順便說一句,你誤解了代碼的工作方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.