javascript - Firebase once() 多次触发
问题描述
我正在尝试在烧瓶应用程序中使用 js 从 firebase 检索数据。虽然它有点工作,但它执行的次数比一次多得多。这是我的代码。我只是想获取消息 ID,将它们保存在数组中,然后在打开聊天框时添加它们。我只希望它执行一次。我能做些什么?
这是我的代码:
//Getting the messages id of the logged in user from firebase and pushing them into the array
firebase.database().ref().child("user-messages").child("{{usuario}}").once('value', function(snapshot) {
console.log(snapshot.val());
snapshot.forEach(function(child) {
console.log("Child: " + child.key + "//////" + child.val());
var msg = {};
msg.key = child.key;
msg.val = child.val();
mensajes.push(msg);
});
});
//Looping the array and looking for the messages on firebase
for(i = 0; i < mensajes.length; i++){
console.log(mensajes);
firebase.database().ref().child("Mensajes").child(mensajes[i].key).once('value', function(childsnapshot) {
var id;
if(mensajes[i].val == "1"){
id = usuario[0].nombre.split(" ")[0];
user = buscarUsuario(childsnapshot.val().to);
} else if(mensajes[i].val == "2"){
user = buscarUsuario(childsnapshot.val().from);
id = user.nombre.split(" ")[0];
}
if (user.user == usuarios[index].user){
if(chat.length){
chat.chatbox("option", "boxManager").addMsg(id, childsnapshot.val().message);
} else{
div.chatbox("option", "boxManager").addMsg(id, childsnapshot.val().message);
}
}
});
}
所以,它的第一次迭代,执行 5 次,只收到 5 条消息:
但是,我得到了这个(不断地不断,永不停息,页面崩溃):
我究竟做错了什么?
提前致谢 :)
解决方案
你once()
在一个for
循环中调用。因此,当然,您可以期望它每次在循环中被调用时执行,长度为mensajes
.
推荐阅读
- php - WordPress 管理菜单突出显示 CPT 的错误项目
- python-3.x - 无法正确读取 Python 中具有深灰色/黑色背景的文本
- bash - 在 vagrant up 期间“无法获得本地颁发者证书”,即使在 vagrant box 添加 --insecure 之后
- jquery-ui - 插件 gulp-less 中的错误:无法解析 jquery-ui.css 中的 alpha
- react-native - 如何检测对 react-native-dropdownalert 的点击?
- java - 对于某些帖子请求,如何跳过杰克逊“unwrap-root-value”?
- javascript - 如何在 React-Native 中将按下事件从内部 Touchable 冒泡到外部 Touchable?
- java - 如何使用 MogoTemplate 应用多个条件条件
- java - 在带有 Java 驱动程序的 mongoDB 中获取最后插入文档的 ID - WITH TYPED COLLECTION
- python - 如何创建字典?