javascript - 为什么更新行为主题功能不起作用
问题描述
updateSubject() {
this.value = false;
this.howToUseObservables();
}
当我按下按钮时会触发此功能,但行为主题没有按预期触发 .next 为什么?
value = true;
constructor() {
this.howToUseObservables().subscribe(ress => alert('in home ' + ress));
}
updateSubject() {
this.value = false;
this.howToUseObservables();
}
updateInOninle(subject: BehaviorSubject<any>) {
subject.next('from func online');
}
updateInOffline(subject: BehaviorSubject<any>) {
subject.next('from func offline');
}
howToUseObservables(): BehaviorSubject<any> {
const testSubjec: BehaviorSubject<any> = new BehaviorSubject('test');
if (this.value === true) {
this.updateInOninle(testSubjec);
} else {
this.updateInOffline(testSubjec);
}
return testSubjec;
}
解决方案
您可能会想,既然您已经alert
从 中删除了响应howToUseObservables
BehaviorSubject<any>
,即使单击按钮,它也会运行,并且您alert
每次单击按钮时都可以看到 。
这不会发生,因为您正在BehaviorSubject<any>
从howToUseObservables
. 因此,除非您subscribe
使用 new BehaviorSubject
,否则您将不会看到in home from func offline
被警告。
尝试使用 ed中subscribe
的return
ed ,您将看到响应已登录到控制台。BehaviorSubject
updateSubject
updateSubject() {
this.value = false;
this.howToUseObservables()
.subscribe(ress => console.log('in home ' + ress));
}
这是您参考的工作示例 StackBlitz。
推荐阅读
- core-data - Previewing ContentView with CoreData
- multithreading - 优化 OpenCL 缓冲区写入?
- pandas - 递归地列出树/有向图中节点的邻居,对于图中的所有节点,一次一个“级别”?
- here-api - Fleet Telematics Waypoints Sequence response time
- java - 在 Scala 中对 Java 列表进行平面映射
- android - 尝试 UnitTest 时,出现 Jacoco 错误。即使它没有使用
- google-cloud-platform - Terraform:自动进行身份验证以将 GCP 存储桶挂载到 VM
- c++ - 在初始化列表中强制转换 shared_ptr
- ios - 如何在 UITableView 中的分隔符附近添加按钮
- python - Intellij Python Selenium 驱动程序函数未从另一个函数调用