【问题标题】:BehaviorSubject with boolean value is not working as intended具有布尔值的 BehaviorSubject 未按预期工作
【发布时间】:2017-01-31 07:08:41
【问题描述】:

我已经实现了一个简单的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

我的实现有什么问题?

【问题讨论】:

    标签: javascript angular rxjs behaviorsubject subject-observer


    【解决方案1】:

    你得到的输出是正确的:

    this.val();
    

    感谢if (res) {...},这只是第一个不打印任何内容的订阅。

    this.changeSt(true);
    

    将值设置为true,由第一次订阅打印。

    this.val();
    

    进行第二个订阅,打印第二个true

    this.changeSt(false);
    

    您将其设置为false,因为if (res) {...} 而被所有订阅者忽略。

    this.val();
    

    同上。

    【讨论】:

      【解决方案2】:

      因为这些行:

      if (res){
        console.log(res);
      }
      

      该值仅在真实时才被记录。

      顺便说一句,您误解了代码的工作方式。

      【讨论】:

        猜你喜欢
        • 2021-05-19
        • 1970-01-01
        • 1970-01-01
        • 2019-01-06
        • 2015-02-25
        • 1970-01-01
        • 2017-12-18
        • 2012-02-02
        • 1970-01-01
        相关资源
        最近更新 更多