Geoff
Geoff

Reputation: 6629

angular2 listening for changes with Firebase

I'm new to Firebase and I would like to listen for changes in the database.

This is what I have tried

constructor(
  private af:AngularFire,
 ){

  this.af.database().ref('registered').on('value', function(snapshot) { //syntax error
    console.log("changed");
  });

  }

How do I listen for changes with Firebase and angular2?

I have also tried setting up on the OnInit

OnInit(){
    this.af.database().ref('registered').on('value', function(snapshot) {
      console.log("changed");
     });

}

and returns an error this.af.database is not a function.

Upvotes: 1

Views: 2472

Answers (1)

Gabriel Barreto
Gabriel Barreto

Reputation: 6421

You're using Angularfire with Firebase SDK syntaxes.

With AngularFire you have to use something like this:

import {Observable} from 'rxjs/Observable';

items: Observable<any[]>;
constructor(af: AngularFire) {
  this.items = af.list('/registered');
}

If you want to use only Firebase sdk you can do this (presuming you have the firebase file on your project):

import firebase from 'firebase';
constructor(){}

OnInit(){
  firebase.database().ref('registered').on('value', snapshot => {
    console.log('changed');
  })
}

EDIT

As said in comment, one can subscribe to a observable in order to execute another function inside of it. This function will be executed until the observable is unsubscribed.

Upvotes: 3

Related Questions