在子值更改事件的回调内时,child_added 快照中缺少 Firebase 数据

标签 firebase

当用户“激活”其帐户后,尝试向用户显示所有用户数据(包括当前用户)时,我遇到了此问题。当监听列表中某个项目的 onValue 更改,然后在回调中监听该列表的 child_added 事件时,原始“监视”项目的快照中会丢失数据。

人工繁殖:

var Firebase = require('firebase');
var rootRef = new Firebase('YOUR-FIREBASE-URL');

var userListRef = rootRef.child('users');

// Clearing the list
userListRef.remove();

// Create a list of users with at least two key/values
var firstUserRef = userListRef.push({name: 'me', active: false});
userListRef.push({name: 'you', active: false});
userListRef.push({name: 'someone', active: false});

// listen for a change to one of the users child data
firstUserRef.child('active').once('value', function(activeData){

    // When the value change callback fires list all of the users data
    userListRef.on('child_added', function(userData){
        console.log(userData.val());
    })

}); 

控制台输出:

{ active: false }
{ active: false, name: 'you' }
{ active: false, name: 'someone' }

名称数据去了哪里?这看起来不像预期的行为,也不是同步问题,因为名称数据应该已经在本地设置。如果我们修改代码来检索整个列表对象,如下所示:

// listen for a change to one of the users child data
firstUserRef.child('active').once('value', function(activeData){

    // When the value change callback fires list all of the users data
    userListRef.on('value', function(usersData){
        console.log(usersData.val());
    })

});

包含所有数据:

{ '-J1ayCVS6B_zVterQWJh': { active: false, name: 'me' },
  '-J1ayCVUUAFP0TL77oaO': { active: false, name: 'you' },
  '-J1ayCVUUAFP0TL77oaP': { active: false, name: 'someone' } }

有人知道这是怎么回事吗?

最佳答案

这是错误的,您将一个事件附加到另一个事件中。没有必要...

示例:

cars (parent node)
----- -J1ayCVS6B_zVterQWJh
----- -J1ayCVUUAFP0TL77oaO
----- -J1ayCVUUAFP0TL77oaP

获取更改

var ref = new Firebase('https://g.com/cars");

ref.on('value', function(snapshot) {
    if (snapshot.val() != null) {

        snapshot.forEach(function(itemDetails) {
            itemDetails.val().username;
            itemDetails.val().active;
        });
    }
});


//and to be serious first attach the event, then you push the records
//assume is a button_click 
var ref2 = new Firebase('https://g.com/cars");

var firstUserRef = ref2.push({name: 'me', active: false});
firstUserRef.push({name: 'you', active: false});
firstUserRef .push({name: 'someone', active: false});

关于在子值更改事件的回调内时,child_added 快照中缺少 Firebase 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18386725/

相关文章:

firebase - Flutter Web 上传到 Firestore

javascript - OnDelete Firebase 触发器不触发

firebase - Firestore 获取文档的值不在数组中?

ios - 测试人员无法从 Firebase App Distribution 下载应用程序

android - Geofire 查询多个引用

java - 如何将firestore中的日期时间存储与当前日期时间进行比较?

swift - 奇怪的不一致的 tableview Swift 4

json - SwiftyJson 和 firestore 时间戳 swift

javascript - Firebase 的云函数获取 key 值

android - 我在向 Android 发送通知时收到 InvalidRegistration