组件更改中的Observable订阅不起作用

时间:2016-12-18 04:35:58

标签: angular firebase firebase-realtime-database rxjs

我在我的组件中订阅了一个可观察的firebase对象。此订阅侦听何时可观察切换从true切换为false,反之亦然。 目前这对我不起作用,它只吐出错误(初始值,即使我知道它在数据库中正确更改。

服务

private ReadyObs;

SetRoom(){
    this.Room = this.AngularFire.database.object('/Rooms/ABC1');
    this.Room.subscribe(snap => {
        if(snap.$value !== null){
            this.ReadyObs = this.AngularFire.database.object(`/Rooms/${player.room}/Ready`);
        }
    }
}

checkReady(){
    return this.ReadyObs;
}

组件

private ReadyObs=this.main.checkReady();

//Always results with still not ready even though its true
this.ReadyObs.subscribe((result) =>{
    if(result === true)
        console.log("Ready to use");
    else
        console.log("Still not ready");
});

1 个答案:

答案 0 :(得分:0)

您的订阅仅采用订阅的初始值,即false。我建议你看看使用主题。 Subject manual link

如果你正在寻找的话,我尝试了一个粗略的例子here

this.ReadyObs=new Rx.BehaviorSubject<boolean>(false);
this.ReadyObs.subscribe((result) =>{
if(result === true)
  console.log("Ready to use");
 else
   console.log("Still not ready");
 });

this.Room.subscribe(snap => {
    if(snap !== null){
      self.ReadyObs.next(true);
     }
  });