我实现了一个简单的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();
与上述相同.
原文地址:https://codeday.me/bug/20190611/1218096.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。