Reputation: 191
I am trying to access user data in a controller via a service. The service returns the object correctly
{
"$id": "9ecadf8e-a233-48ac-bebf-26b50ea2855d",
"$priority": null,
"branch": "London",
"email": "[email protected]",
"firstName": "John",
"lastLogin": 1467975594697,
"lastLoginPrevious": 1467975348837,
"lastName": "Smith",
"role": "Manager"
}
when accessing the data from the controller I can access the $id
successfully by using
$scope.userData = UserService.getUserData();
console.log($scope.userData.$id)
but when trying to access any other node such as role
$scope.userData = UserService.getUserData();
console.log($scope.userData.role)
I just get 'undefined' in the console. Obviously I am not doing this correctly but stuck on what I should try next.
Here is my service that retrieves the data from firebase
.service('UserService', ['$location', '$firebaseAuth','$firebaseObject', function ($location, $firebaseAuth, $firebaseObject) {
var userData = '';
var ref = new Firebase("https://firebase-url");
var authData = ref.getAuth();
var userUID = authData.uid;
var userRef = new Firebase("https://firebase-url/Users/" + userUID);
var userData1 = $firebaseObject(userRef);
return {
getUserData: function () {
if (userData == '') {
userData = userData1;
}
return userData;
},
};
Upvotes: 0
Views: 1438
Reputation: 7927
You could possibly be having an asynchronous issue. Here is an example of my code in a controller (Firebase 3.0):
// Gets reference to resources tree, SERVICE CALL
$scope.resourceNames = submissions.getResourceNames();
// Could be previously loaded, check
if(Object.keys($scope.resourceNames).length === 0 && $scope.resourceNames.constructor === Object) {
// Get reference
var resourceNameRef = firebase.database().ref("/resourceNames");
firebase.database().goOnline();
// Return JSON object of data at specified location
$scope.resourceNames = $firebaseObject(resourceNameRef);
// When resources loaded
$scope.resourceNames.$loaded().then(function(data) {
// Store into service, SERVICE CALL
submissions.setResourceNames(data);
// DO WHATEVER
}).catch(function(error) {
console.error("Error:", error);
});
} else {
// WAS ALREADY LOADED
}
What I have done is check the service to see if the data has already been loaded (by another controller) and if it wasn't I call the data, wait for it to be loaded and then store it inside my service.
I can then use the data as I please inside the controller or in the view:
<p>
{{resourceNames.$id}}
</p>
<p>
{{resourceNames.name}}
</p>
<!-- etc -->
Upvotes: 1