我试图通过服务访问控制器中的用户数据。该服务正确返回对象
{
"$id": "9ecadf8e-a233-48ac-bebf-26b50ea2855d",
"$priority": null,
"branch": "London",
"email": "manager@london.co.uk",
"firstName": "John",
"lastLogin": 1467975594697,
"lastLoginPrevious": 1467975348837,
"lastName": "Smith",
"role": "Manager"
}
从控制器访问数据时,我可以使用
成功访问$id
$scope.userData = UserService.getUserData();
console.log($scope.userData.$id)
但是在尝试访问任何其他节点时,例如角色
$scope.userData = UserService.getUserData();
console.log($scope.userData.role)
我只是得到了未定义的'在控制台中。显然我没有正确地做到这一点,但坚持下一步我应该尝试。
这是我的服务,它从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;
},
};
答案 0 :(得分:1)
您可能遇到异步问题。以下是我在控制器中的代码示例( 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
}
我所做的是检查服务以查看数据是否已经加载(由另一个控制器),如果我没有调用数据,等待它加载,然后将其存储在我的内部服务。
然后我可以在控制器内或视图中使用数据:
<p>
{{resourceNames.$id}}
</p>
<p>
{{resourceNames.name}}
</p>
<!-- etc -->