Cannot access Firebase object attributes. Value displayed as undefined ANGULARFIRE

风流意气都作罢 提交于 2019-12-19 09:23:44

问题


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
};

}]);


回答1:


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.



来源:https://stackoverflow.com/questions/25450325/cannot-access-firebase-object-attributes-value-displayed-as-undefined-angularfi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!