0

I'm trying to reference child data within an object returned from a factory using Firebase, but I'm stumped. I can successfully get the user object that I want ($scope.user), but I can't seem to reference the data inside of it (such as $scope.user.name) - everything returns undefined.

app.factory('Data', ['$firebase', function(){
    var ref = new Firebase('https://something.firebaseio.com/users');
    return {
        refUser: function(id){
            return $firebase(ref.child(id)).$asObject();
        }
    }
}]);

app.controller('MainCtrl', ['Data', function(Data){
    $scope.user = Data.refUser(123); // 123 = user ID
    console.log($scope.user); // Returns user object successfully (containing 'name' key)
    console.log($scope.user.name); // Return undefined
}]);

What is it that I'm missing? I'm not quite sure where the problem even lies with my understanding: Angular, Firebase, or simple javascript.

scferg5
  • 2,003
  • 5
  • 22
  • 28
  • Maybe your user.name === undefined ? – alexpods Jan 07 '15 at 17:35
  • 2
    The `$asObject` returns a promise, which at some point in the future will contain the user's properties. I'll write a short answer (which lots of references to similar questions). Never mind, it looks like Mathew Berg just beat me to that. :-) – Frank van Puffelen Jan 07 '15 at 17:37
  • See http://stackoverflow.com/questions/27049342/asynchronous-access-to-an-array-in-firebase/27050749#27050749 and http://stackoverflow.com/questions/26604472/firebase-angularfire-child-asobject-give-properties-undefined/26673597#26673597 – Frank van Puffelen Jan 07 '15 at 17:40
  • @Frank Thanks for making me understand the issue! You've certainly been a great resource for these issues. – scferg5 Jan 07 '15 at 19:00
  • You're welcome. I hope between my links and Mathew's answers, things are clearer now. Unfortunately the asynchronous nature of the web is always a bit tricky. But fortunately with Firebase you get real-time data updates in return, which is awesome. :-) By the way: don't forget to accept Mathew's answer if that helped too. – Frank van Puffelen Jan 07 '15 at 19:03
  • `return { return { return $firebase(...) } }` make it stop, Frank! Make it stop! – Kato Jan 12 '15 at 18:50
  • `Data` could return more than just `refUser`, but I took them out for simplicity. Guess I could have simplified it even more. ;) – scferg5 Jan 12 '15 at 20:33

1 Answers1

3

It's because the refUser is still making a call and it hasn't finished getting it yet. The reference for $scope.user exists because it has already been created. If you change your console.log to console.log(JSON.stringify($scope.user)); you'll see that it is actually empty. Chrome dev tools keeps the reference that is filled after the call has completed.

Mathew Berg
  • 28,625
  • 11
  • 69
  • 90