【问题标题】:subscribing to observable even when next is not called on BehaviorSubject即使没有在 BehaviorSubject 上调用 next 也订阅 observable
【发布时间】:2018-12-21 11:19:51
【问题描述】:

我有一个简单的场景:

service.ts:

  private showComposeBoxAction = new BehaviorSubject<boolean>(null);
  showComposeBox = this.showComposeBoxAction.asObservable();


  openComposeBox(event:boolean) {
    console.log("in openComposeBox");
    this.showComposeBoxAction.next(event);
  }

组件.ts:

 constructor(
    private _service: Service,

  ) {

    this.subscriptions.add(
      this._mailingService.showComposeBox.subscribe(event => {
        if (event) {
          this.displayCompose = true;
          console.log("showComposeBox displayCompose", this.displayCompose);
        }
      })
    );

}

component2.ts:

  showComposeBox() {

    if (this.count === 0) {
      this._service.openComposeBox(true);
    }
  }

我在 openComposeMsg() 中记录了一条消息。 我面临的问题是我第一次正确订阅 showComposeBox observable 但第二次订阅时即使没有调用 next 也是因为 msg "in openComposeBox" 没有登录到控制台。

无法理解 BehaviorSubject 的行为。 我做错了什么?

【问题讨论】:

  • 你的服务是单例吗?
  • @JBNizet Hi 正在使用 BehaviorSubject。它保存当前数据并在订阅者订阅后立即传递给订阅者
  • @Simer 好吧,这就是 BehaviorSubject 的重点:它有一个当前值,每次订阅时,都会立即通知您当前值。如果这不是您想要的,那么您一开始就不应该使用 BehaviorSubject。
  • 我应该使用主题吗?可能是。阅读文档。
  • 是的。如果您使用它记录的内容之前阅读它,您将节省,从而更容易遵守截止日期。

标签: angular angular2-observables angular-observable


【解决方案1】:

我在 JB Nizel 和 Suren Srapyan 的指导下解决了我的问题。通过用主题替换行为主题。由于 observable 在构造函数中被订阅,它触发并使用行为主体的当前保存值,该值之前由其他函数设置为 true。

参考自This SO 但是现在面临另一个问题,即调用 openComposeBox 并记录 msg,即使未订阅 observable 也是如此。当我得到解决方案时,我会更新答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-17
    • 2023-04-09
    • 2018-09-19
    • 2021-07-30
    • 2019-07-18
    • 1970-01-01
    相关资源
    最近更新 更多