首页 > 解决方案 > 为什么更新行为主题功能不起作用

问题描述

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;
  }

标签: javascriptangularionic-frameworkrxjsbehaviorsubject

解决方案


您可能会想,既然您已经alert从 中删除了响应howToUseObservables BehaviorSubject<any>,即使单击按钮,它也会运行,并且您alert每次单击按钮时都可以看到 。

这不会发生,因为您正在BehaviorSubject<any>howToUseObservables. 因此,除非您subscribe使用 new BehaviorSubject,否则您将不会看到in home from func offline被警告。

尝试使用 ed中subscribereturned ,您将看到响应已登录到控制台。BehaviorSubjectupdateSubject

updateSubject() {
  this.value = false;
  this.howToUseObservables()
    .subscribe(ress => console.log('in home ' + ress));
}

这是您参考的工作示例 StackBlitz


推荐阅读