我在我的应用程序中使用firebase实时数据库进行聊天功能,我只需要返回一个Obserable of type any或者从firebase查询中输入Message, 这是我的代码:
getMessageHistory(farmerId) {
let chatMessages = [];
var chats;
firebase.database().ref('/' + this.chatUrl + '/' + farmerId + '/').once('value', function (snapshot) {
chats = snapshot.val();
if (chats != null) {
Object.keys(chats).forEach(element => {
let chat = chats[element.toString()];
var Message = {
fromId: chat.from,
toId: chat.to,
message: chat.message
}
let mockedHistory: Array<Message>;
mockedHistory.push(Message)
});
}
else {
}
});
}`
如何从上面的方法返回Observable。我尝试过angularfire2但在编译时抛出错误(Angular Version 4)
答案 0 :(得分:0)
得到了解决方案,但我不知道是否推荐!
let mockedHistory: Array<Message> = [];
let totalRecords = this.db.list('/' + this.chatUrl + '/' + userId + '/');
return totalRecords.valueChanges<any>().map((chat)=>{
var newChat = chat.map((message) => {
let msg = new Message();
msg.fromId = message.from;
msg.toId= message.to,
msg.message= message.message
return msg;
});
return newChat;
}
)