Pregunta

I am just trying to get a value out of my firebase using angularjs and angularfire...having issues.

Inside my controller:

$scope.componentStatus = syncData("components/-JI_JgHxm0TEUEVjADJn/status");
console.log($scope.componentStatus);

This returns an object which has $value as one of the objects within it.

BUT, when I try:

console.log($scope.componentStatus.$value);

I get Undefined as the result.

Any pointers? I feel like this should be an easy task, so I'm just missing something.

Versions Used
https://cdn.firebase.com/v0/firebase.js
Angularjs - 1.2.7
Angularfire - 0.6.0

Data Structure

components : {
    "-JI_dFtOxE5k1ZFeZu8a" : {
      "experience" : "-JJ8jT0oJA3vYOeBNpq5",
      "name" : "Name of Component",
      "status" : "-JJ8hQcUb0_ip9Hoqcqq",
      "theme" : "-JJ8mD9tEsBw3a3g9Wz6"
    },
}
¿Fue útil?

Solución

This is a simple misunderstanding of asynchronous processes. At the time that you call $value, the data has not been fetched from the server yet.

Try calling this inside a $on('loaded', ...) callback:

$scope.componentStatus = syncData("components/-JI_JgHxm0TEUEVjADJn/status");
$scope.componentStatus.$on('loaded', function() {
    console.log($scope.componentStatus.$value);
});

Note that if what you're actually trying to do is display this in the DOM, there's no need to worry about when the data arrives--Firebase and Angular will work it out on their own:

<div>When it arrives, it will appear here: {{componentStatus.$value}}</div>

Here's a fiddle demonstrating these concepts: http://jsfiddle.net/katowulf/e7WFf/

And another showing the same idea with $bind: http://jsfiddle.net/katowulf/4J356/

As of angularFire 0.8.0, you will also be able to treat the $firebase object as a promise with something similar to this:

var data = syncData("components/-JI_JgHxm0TEUEVjADJn/status").then(function() {
    console.log(data.$value);
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top