我正在尝试做一些应该相当简单的事情-从我的Firebase DB中加载一个对象,并将其分配给我的控制器中的一个变量。以前,当我使用Firebase函数(参见注释掉的代码)时,这个方法工作得很好,但我想使用3-way绑定,所以我在AngularFire中尝试做同样的事情。
$loaded事件似乎不会触发,因为规划器对象(也不是“你在这里”)从不打印到控制台。user.uid字符串按预期打印到控制台,并且注释掉的代码可以很好地工作。提前感谢您的帮助。
(附带问题:在注释掉的代码中,我使用evalAsync来确保在检索信息时web页面上的表单实际更新-这是一个好做法吗?)
我的控制器:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log("Currently logged in user...");
console.log(user.uid);
$scope.user = user;
var ref = firebase.database().ref('planners/' + $scope.user.uid);
var planner = $firebaseObject(ref);
planner.$loaded().then(function() {
console.log("You are here")
console.log(planner)
})
.catch(function(error) {
console.log(error)
})
// firebase.database().ref('planners/' + $scope.user.uid).on('value', function(response) {
// if (response.val() != null) {
// $scope.$evalAsync(function() {
// $scope.planner = response.val();
// })
// }
// });
}
else {
console.log('No user logged in')
$state.go('login')
}
})发布于 2016-08-01 05:46:25
试着改变这个...
firebase.auth().onAuthStateChanged(function(user) {对这个..。
$firebaseAuth().$onAuthStateChanged(function(user) {有关详细信息,请参阅文档
发布于 2016-08-07 17:03:04
正如@Aaron Saunders建议的那样,你应该使用AngularFire身份验证对象,因为它可以更好地与Angular集成(更新$scope,触发器$digest等)。
以前的代码之所以能够工作,是因为$evalAsync会在$digest未运行时触发它( $digest循环是绑定模型和视图之间数据的魔术师)。
您实际应该做的是使用AngularFire绑定数据。它们还利用$bindTo提供了“三向绑定”(模型-视图-数据库)。
正如您在$firebaseObject docs中看到的,数据将自动从服务器同步到客户端,但如果您希望将本地更改保存回服务器,则应使用$save或$bindTo。
代码修复建议:
$firebaseAuth().$onAuthStateChanged(function(user) {
// By using `$firebaseAuth` this function will be called in a `$digest` so all changes will be bound
if (user) {
console.log("Currently logged in user...");
console.log(user.uid);
$scope.user = user;
var ref = firebase.database().ref('planners/' + $scope.user.uid);
// `$destroy` previous bindings
if ($scope.planner && angular.isFunction($scope.planner.$destroy)) {
$scope.planner.$destroy();
}
$scope.planner = $firebaseObject(ref);
// planner.$loaded().then(function() {
// // This code will happen only after `$digest` since its promise is relied on the `$q` service
// console.log("You are here")
// console.log(planner)
// })
// .catch(function(error) {
// console.log(error)
// })
// firebase.database().ref('planners/' + $scope.user.uid).on('value', function(response) {
// if (response.val() != null) {
// $scope.$evalAsync(function() {
// $scope.planner = response.val();
// })
// }
// });
} else {
console.log('No user logged in');
$scope.user = null;
if ($scope.planner && angular.isFunction($scope.planner.$destroy)) {
$scope.planner.$destroy();
}
$state.go('login');
}
});https://stackoverflow.com/questions/38677541
复制相似问题