2017-09-27 88 views
0

我有两个数据库,我想咨询两个数据并将结果存储在唯一数组中。问题是:出于某种原因,相同的值被一次又一次地推向数组,而不是每个值。将火力点值推入数组

chats = []; 
chat = {}; 

    firebase.database().ref("users").child(this.AngularFireAuth.auth.currentUser.uid).child("chats").on("child_added", (data) => { 
     this.chat = {}; 
     this.chat['topic'] = data.val().topic; 
     console.log("1"); 
     firebase.database().ref("users").child(data.val().otherUserUid).once("value", (data) => { 
     this.chat['otherUsersName'] = data.val().name; 
     this.chat['otherUsersPhoto'] = data.val().photo; 
     console.log("1"); 
     }).then(()=>{ 
     this.chats.push(this.chat); 
     console.log("3"); 
    }); 
    }); 

我想什么this.chats数组是:

[ 
    {topic: "Tech", otherUsersName: "Jonh Turner", otherUsersPhoto: "jonh_profile.png"}, 
    {topic: "Food", otherUsersName: "Paul Kant", otherUsersPhoto: "paul_profile.png"}, 
    {topic: "Science", otherUsersName: "Jimmy Poer", otherUsersPhoto: "jimmy_profile.png"} 
] 

我得到什么:

[ 
    {topic: "Tech", otherUsersName: "Jonh Turner", otherUsersPhoto: "jonh_profile.png"}, 
    {topic: "Tech", otherUsersName: "Jonh Turner", otherUsersPhoto: "jonh_profile.png"}, 
    {topic: "Tech", otherUsersName: "Jonh Turner", otherUsersPhoto: "jonh_profile.png"} 
] 

我多么希望控制台是:

1 
2 
3 
1 
2 
3 
1 
2 
3 

我得到:

1 
1 
1 
2 
2 
2 
3 
3 
3 
+0

你'child_added'回调中的第一行:'this.chat = {};' - 什么是每次在该路径添加新的DB值时清除该变量的目标是什么? –

+0

,这样只有当前的孩子被添加到数组中。如果我没有清除它,所有过去的孩子也将被推,这将导致很多重复的孩子 – jonhz

回答

0

好像你要

firebase.database() 
.ref("users") 
.child(this.AngularFireAuth.auth.currentUser.uid) 
.child("chats") 
.on("child_added", (data) => { 
    firebase.database() 
    .ref("users") 
    .child(data.val().otherUserUid) 
    .once("value", (dataother) => { 
     this.chats.push({ 
      topic: data.val().topic, 
      otherUsersName: dataother.val().name, 
      otherUsersPhoto: data.val().photo 
     }); 
    }); 
}); 

注意dataother在内部调用

+0

感谢您的答案,但仍然无法正常工作 – jonhz