当按时间戳排序firebase ref时,Observable会两次触发

时间:2018-01-08 22:12:47

标签: angular firebase firebase-realtime-database chat ionic3

我正在使用firebase创建聊天应用。当聊天有新消息时,我添加了一个observable。我的prb是,当我按时间戳订购消息时,消息显示两次,即使保存消息功能仅按时运行。 这是可观察的:

return new Observable((observer) => {
  var result = [];
  var lastMessage;
  var order = 'msgId';
  this.db.ref('/chats/' + channelId + '/messages').orderByChild(order).startAt(lastMsgId)
   .once('value', snapshot => {
    snapshot.forEach((childSnapshot) => {
      result.push(childSnapshot.val())
      return true;
    })
    if(result.length)
      lastMsgId = result[result.length-1].msgId + 1;
      observer.next(result);
    })
})

保存到数据库功能:

saveMessageToDatabase(currentUserId, otherUserId, channelId, message) {
    messageObj = {
      key: channelId,
      msgId: lastActivity,
      message: message,
      uid: currentUserId,
      timestamp: lastActivity
    };
  this.db.ref('/chats/' + channelId + '/messages/').push(messageObj)
}

1 个答案:

答案 0 :(得分:0)

在您的服务(推荐)/组件中:

constructor(private angularFireDatabase: AngularFireDatabase) {}

// lastMsgId: number | string
OnGetMessages(channelId: string, order: string, lastMsgId: number){
    return this.angularFireDatabase
      .list(`/chats/${channelId}/messages `, 
      ref => ref.orderByChild(order).startAt(lastMsgId))
      .valueChanges();
}

在您的组件中:

myMessages: any
//if you used service you should provide it in constructor.
constructor(private firebaseService: FirebaseService) {}

ngOnInit(){
  // you can esle where in other function, ngOnInit used just for example.
  this.firebaseService.subscribe((msgs)=>{
      console.log(msgs);
      this.myMessages = msgs;
    })
}

让我知道它是否有用。祝你好运。