将firebase值推送到数组

时间:2017-09-27 02:26:40

标签: javascript firebase

我有两个数据库,我想咨询并将两者的结果存储在一个唯一的数组中。问题是:由于某种原因,相同的值被反复推送到数组,而不是每个值。

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

1 个答案:

答案 0 :(得分: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