4

I want to do a custom login for a demo of my doing, but I encountered a problem.

I use the username to access a reference url inside Firebase, I get a returned object. If I want to access a single attribute, I get the undefined value, but if I add in my html {{returnedObj.name}} the value is displayed.

Why is that?

angular.module('Demo').controller('loginCtrl', ['$scope', '$firebase', '$location',    function($scope, $firebase, $location){
$scope.user = {};
$scope.check = function(){
    console.log('https://fabritzio-demo.firebaseio.com/users/' + $scope.user.name);
    $scope.returnedObj = $firebase(new Firebase('https://fabritzio-demo.firebaseio.com/usuarios/' + $scope.user.name)).$asObject();
    alert($scope.returnedObj.name); // returns undefined value
};

}]);

6
  • Firebase values are loaded asynchronously. Is it possible that the value hasn't loaded yet when the alert fires? Commented Aug 22, 2014 at 15:17
  • 1
    Try $scope.returnedObj.$loaded().then(....) ? Commented Aug 22, 2014 at 15:18
  • 1
    I just tried $scope.returnedObj.$loaded().then(function(){alert($scope.returnedObj.name)}). It displays the value. Is there an explanation? I would like to understand the cause Commented Aug 22, 2014 at 15:25
  • The cause is what @afternoon said already: Firebase loads the values asynchronously. So by calling $loaded you ask it for a so-called promise object for when the data is actually loaded. By calling then you can then execute code after the data has loaded. Commented Aug 22, 2014 at 18:26
  • There are many similar examples of asynchronous operations, though most of them will take a callback function instead of working with promises. E.g. the regular (non-Angular) Firebase API uses a ref.on('value', function(snapshot) { /* your code here */ }) construct. The function is called when the value is first available or whenever it changes. This is another example of an asynchronous call. Commented Aug 22, 2014 at 18:28

1 Answer 1

12

Firebase values are loaded asynchronously. The value will not yet have been loaded into $scope.returnedObj when the alert fires.

There are a couple of ways to handle values loading asynchronously from Firebase, for example using $loaded to get a promise:

$scope.returnedObj.$loaded().then(function () {
  alert($scope.returnedObj.name);
});

The value is displayed in the template because Angular watches all $scope variables for changes. When the value is loaded (milliseconds later), it is immediately displayed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.