Mpondomise Mpondomise - 1 month ago 20
AngularJS Question

angularjs rootscope user database info from firebase

I am trying to fetch user info from user's database and access it from anywhere using rootscope.
I get the user's email and uid as the user signs in.
However,to get the user's info from database, I need to call my database and read the info one by one and store it as a variable in rootscope to access it from everywhere.


So, my question is below :




  • How can I use rootscope in this example?

  • Is there any better way to do this?

  • in the below example, the console log is showing the first name, but I don't know how to rootscope it?



Thanks for help.

app.run(['$rootScope', '$state', '$stateParams', '$cookies', "$location",
function ($rootScope, $state, $stateParams, $cookies, $location) {

firebase.auth().onAuthStateChanged(function(user) {
if (user) {

$rootScope.user.uid = user.uid;
$rootScope.user.email = user.email;

return firebase.database().ref('/users/' + user.uid).once('value').then(function(snapshot) {

var firstname = snapshot.val().firstname;
console.log("first name", firstname);

});
} else {
// No user is signed in.
}
});
}]);

Answer

If you use AngularFire Always use its wrapper methods vs native firebase methods.

Do not use

firebase.auth().onAuthStateChanged
firebase.database().ref('/users/' + user.uid).once('value')

Use

$firebaseAuth().$onAuthStateChanged
var userData = $firebaseObject(firebase.database().ref('/users/' + user.uid));

Checkout the following link for full list of available methods in angularFire. https://github.com/firebase/angularfire/blob/master/docs/reference.md

I recomend modifying your code like this.

$firebaseAuth().$onAuthStateChanged(function(user) {
    if (user) {
      $rootScope.user = $firebaseObject(firebase.database().ref('/users/' + user.uid));
      $rootScope.user.uid = user.uid;
      $rootScope.user.email = user.email;
      console.log("Here you should have complete user object");
      // still if you want to do something when user is loaded
      /* $rootScope.user.$loaded(function(loadedUser) {
            var firstname = loadedUser.firstname;
            console.log("first name", firstname);
        });*/
    } else {
        // No user is signed in.
    }
});

Of course you need to include $firebaseObject and $firebaseAuth using dependency injection.