How to get current value from a BehaviorSubject in AngularFire2?

1k views Asked by At

I'm using AngularFireDatabase to get part of my database like this db.object('/accounts/'+this.cid); where this.cid is a BehaviorSubject which can change. Am I going about this the wrong way?

cid: BehaviorSubject<string>;
account: FirebaseObjectObservable<any>;
constructor(private db: AngularFireDatabase) {
  this.cid = new BehaviorSubject<string>('fs2ejD4ds');
  this.account = db.object('/accounts/'+this.cid);

Basically whenever I run this.cid.next('fhEj2jd') I want it to change which object we're trying to reference in Firebase.

1

There are 1 answers

0
Pengyy On BEST ANSWER

For getting current value from BehaviorSubject, you can call it's getValue method, see docs.

this.account = db.object('/accounts/'+this.cid.getValue());

But keep in mind that you will have to overwrite the original observable this.account each time this.cid's current value has been changed. And If you simply subscribe to this.account, then you will have to unsubscribe before overwrite it with new observable(for unsubscribe, you can use async pipe to do it automatically).

Refer simple demo.