2017-09-27 89 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