我正在使用 Angular 和 Firebase 构建一个应用程序,其中一个方面是一对一聊天。我正在查询 Firebase 以查看当前访问应用程序的用户和他们试图与之聊天的用户之间是否已经存在聊天室。如果它存在,我将尝试将该房间作为所选房间应用于范围。我正在使用“消息”服务来运行查询。
this.roomQuery = function(user1ID, user2ID) {
roomsRef.orderByChild("user1").equalTo(user1ID).on("child_added", function(snapshot) {
if (snapshot.val().user2 == user2ID) {
self.selectedRoom = snapshot.key();
console.log(self.selectedRoom);
} else {
self.selectedRoom = null;
}
})
}
在我的 Controller 中,我正在使用:
$scope.$watch(
function(){ return Messages.selectedRoom },
function(newValue, oldValue) {
$scope.selectedRoom = newValue;
}
)
这个 $scope.$watch
方法对我来说对其他所有事情都有效,并且它似乎有时在这种情况下有效。控制台日志总是打印出 Messages.selectedRoom 的正确值,但 $scope.selectedRoom 有时不会更新。知道这里发生了什么吗?我很困惑。如果它正确地登录到控制台,是否应该在范围内更新它?
最佳答案
Angular 的 $digest
不知道您的 Firebase 查询何时完成。您可能会发现使用 AngularFire 更容易在这种情况下。
this.roomQuery = function(user1ID, user2ID) {
var query = roomsRef.orderByChild("user1").equalTo(user1ID);
return $firebaseObject(query).$loaded();
};
this.roomQuery("1", "2")
.then(function(data) {
// do your check here
});
$firebaseObject()
接收引用或查询,并知道何时代表您调用摘要。
您可能想查看 using resolve
in the router将 roomQuery
注入(inject)路由器,因为它返回一个带有 .$loaded()
的 promise 。
关于javascript - 在 angularjs 中观看 Firebase 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34123454/