0

I am trying to get the user data from my local storage using a firebase api. In the run method i have a simple bit of code to call it

$rootScope.$on('$stateChangeStart', function () {
          // Use the User service to get the currently 
          // logged in user from the local storage
          var loggedInUser = User.getLoggedInUser();
          //
          if (loggedInUser) {
              $rootScope.loggedInUserData = User.getUserData(loggedInUser.uid);
          }
      })

Which does call it. The service simply takes the user and i getItem with a JSON parse

var user = localStorage.getItem('firebase:session::<foo>');
if (user) {
    return JSON.parse(user);
}

in my controller if i write a simple console.log($rootScope.loggedInUserData) it returns the data as expected.

expected return

However if i add console.log($rootScope.loggedInUserData.email) i get an undefined

What is even stranger is if i include both console.log($rootScope.loggedInUserData.email) and console.log($rootScope.loggedInUserData) then the $rootScope.loggedInUserData structure changes to the image below

enter image description here

The only change i have made in the code between the two images is the addition of console.log($rootScope.loggedInUserData.email) .

Anyone have any insight into this? I would like to be able to reuse it as a firebaseObject in order to update changes to the user.

UPDATE

I was able to get the email using the angularfire $loaded() method

  $rootScope.loggedInUserData.$loaded()
     .then(function (data) {
        console.log(data.email); // returns
   })

i am guessing this has to do with my slow connection.

  • Can you be more specific about where you are adding the console.log statements? Also, is there anywhere else in the app that you are (re)setting the $rootScope.loggedInUserData variable? – GPicazo Aug 19 '15 at 18:23
  • its in a controller. Just a standard controller with nothing in it. I am not using the $rootScope variable anywhere else. I think this has something to do with the time it is taking to fetch the data from firebase. If i used the angularfire `$loaded` then i am able to get the email. –  Aug 19 '15 at 18:28
  • Sounds like you've got a good diagnosis and solution. If the data is sometimes ready by the time it runs console.log, then if you keep refreshing the page it should sometimes work, sometimes not. That should prove that it's a race condition. – HankScorpio Aug 19 '15 at 18:41

0 Answers0