LaSul
LaSul

Reputation: 2421

Angular 4 + Firebase getting the value out of a snapshot when requesting database

I'm trying to get items out of a Firebase DB, but it looks I can't. The operator "this" is not working in the snapshot function (on the line this.authState.prenom = snapshot.val().prenom)

And If I do it outside the function, it seems it's executed before the function, so the attribute is empty. The only solution I found is to put a timeout (one the line setTimeout( () => this.authState.prenom = prenom,1000)" but it's not what I want.

I just want the declaration this.authState.prenom = prenom; executed after the snapshot function is over or getting the value out of this snapshot function in any way.

Here is my file (variables are all declared)

auth.service.ts Here is the constructor :

  constructor(private afAuth: AngularFireAuth,
  private db: AngularFireDatabase,
  private router:Router) {

this.afAuth.authState.subscribe((auth) => {
  this.authState = auth;

  if(this.currentUser){
    var userId = this.currentUser.uid;

    var prenom: any;
    var nom: any;

    firebase.database().ref('/users/' + userId).on('value',function(snapshot) {
      // this.authState.prenom = snapshot.val().prenom; <= This is not working because I can't use "this" operator here and don't know why

      console.log(snapshot.val().prenom);
      console.log(snapshot.val().nom);

      prenom = snapshot.val().prenom;
      nom = snapshot.val().nom;

      // this.authState.nom = snapshot.val().nom; <= not working because of the operator "this"
    });
    this.authState.prenom = prenom // <= Not working because it's executed before the snapshot function and don't know why
    setTimeout( () => this.authState.prenom = prenom,1000); // <= This is working but setting timeout is not a good thing..
    setTimeout( () => this.authState.nom = nom,1000);
    // console.log(this.authState.prenom);
  }
}

Upvotes: 1

Views: 1297

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600100

To get the this working, use fat arrow function notation (as you do with the auth.subscribe):

firebase.database().ref('/users/' + userId).on('value', (snapshot) => {
  this.authState.prenom = snapshot.val().prenom;
  this.authState.nom = snapshot.val().nom;
});

Some more old-school alternatives:

var that = this; // capture the correct this in a variable
firebase.database().ref('/users/' + userId).on('value', function(snapshot) {
  that.authState.prenom = snapshot.val().prenom;
  that.authState.nom = snapshot.val().nom;
});

Or:

firebase.database().ref('/users/' + userId).on('value', function(snapshot) {
  this.authState.prenom = snapshot.val().prenom;
  this.authState.nom = snapshot.val().nom;
}, this); // pass in the this as the last parameter

For more information, I highly recommend reading How to access the correct `this` inside a callback?

Upvotes: 3

Related Questions