rycirese
rycirese

Reputation: 199

Observe firebase database on changes typescript

So I'm calling to my firebase realtime database in an angular service like so:

readItems() {
    return this.af.database.ref(`/path`)
      .on('value', snap => this.callback(snap.val()));
  }

callback just modifies the response to my needs. What I need to do is grab this modified data in the component I'm calling readItems from. Here's that call in said component:

this.service.readItems();

I want to to find when this finishes and returns the modified response using an observable or promise with a subscribe or then. I cannot figure how to do this and any help would be great.

Upvotes: 0

Views: 634

Answers (1)

Boris Lobanov
Boris Lobanov

Reputation: 2454

You can use a Subject from rxjs in the callback you pass into the on function and subscribe to it:

valueChanged$ = new Subject();

callback(val) {
    // some code ...
    valueChanged$.next(val); // pass whatever you need to receive in the subscription
}

readItems() {
  return this.af.database.ref(`/path`)
    .on('value', snap => this.callback(snap.val()));
}

Then later in your code:

this.valueChanged$.subscribe(data => doStuff(data));
this.service.readItems();

Upvotes: 2

Related Questions