Firebase: how to properly return data?


#1

Hey everyone here’s the deal.

I have an provider that is used to retrieve data from database, so when my user logs in i need to get his profile data from my ‘Users’ node.
Here is my code before i make things clear (i’ll post just the needed code, no alerts and loading or anything like this):

LOGIN.ts:

//First i call my login method
this.auth.login(this.login.get('emailLogin').value,
  this.login.get('senhaLogin').value).then(data => {
    
    // Then i get the returned data and uses the uid to get my
    // UserProfile on 'Users' database node.
    let retorno;
    // i need my user data to be returned here so i can send it as a
    // parameter in navCtrl.push()
    retorno = this.auth.buscaPerfil(data.uid, false);
    console.log(retorno);
    this.navCtrl.push(PacienteHomePage);
  }, err => {
    *error message*
  }
});

AUTH.ts (the login is working, so i’ll just post the data retriever method):

//buscar perfil
buscaPerfil(uid, medico: boolean) {
    if (medico) {
        this.novoUsuario.child(uid).on('value', snapshot => {
            console.log('buscou medico');
            this.storage.set('medico', medico);
            this.storage.set('id', uid);
            this.storage.set('nome', snapshot.val().nome);
            this.storage.set('genero', snapshot.val().genero);
            this.storage.set('email', snapshot.val().email);

            //here i'm trying to return a part of my data to the login.ts
            return { nome: snapshot.val().nome, genero: snapshot.val().genero };
        });
    } else {
        console.log('buscou paciente');
        this.novoUsuario.child(uid).on('value', snapshot => {
            this.storage.set('medico', medico);
            this.storage.set('id', uid);
            this.storage.set('nome', snapshot.val().nome);
            this.storage.set('genero', snapshot.val().genero);
            this.storage.set('email', snapshot.val().email);
            this.storage.set('telefone', snapshot.val().telefone);
            return { nome: snapshot.val().nome, genero: snapshot.val().genero };
        });
    }
}

So i need to return the data to my variable in login.ts but i get undefined. What i need to do? Do i have to use AngularFire with subscribe? Is there another method i could call?


#2

Side note: You should stick to English for your variable and method names, this is hard to go through. The mix of the standard English keywords and your native language is weird.

I’m not sure why you expect buscaPerfil to return anything other than undefined since I cannot see that you return anything at all in that function. There’s so much context missing that it’s hard to tell you anything useful.

Look into Promises and Observables, if you need to work with asynchronous values/interfaces.