I am implementing chat feature in my project and for that have used chat library and as a database for a chat, I am using Firebase Real-time Database.
There are two methods: One is getMessageHistory()
[Which is used to get the message history of users message] and another one is getMessageHistoryFromFirebase()
[Which is used to get the message history of users message from FIREBASE real-time database]
PROBLEM: When I am calling getMessageHistoryFromFirebase()
method in getMessageHistory()
it gets called and but called late and the current execution of parent method is reached to an end.
How do I get data from firebase (by getMessageHistoryFromFirebase()
method) and then fill the mockedHistory
array with firebase database?
Even I know the method get called early and at the time of initialization the current list is empty:
Every response will be highly appreciated!
Class file :
Parent Method :
getMessageHistory(userId: any): Observable<Message[]> {
let firebaseMessages = this.getMessageHistoryFromFirebase(userId);
let mockedHistory: Array<Message>;
mockedHistory = firebaseMessages;
// mockedHistory = [
// {
// fromId: userId,
// toId: userId,
// message: "Hi there, just type any message bellow to test this Angular module."
// }
// ];
return Observable.of(mockedHistory);
}
Child Method :
getMessageHistoryFromFirebase(farmerId) : any{
let chatMessages = [];
var chats;
var database = firebase.database();
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
}
chatMessages.push(Message)
});
}
});
return chatMessages;
}
It works fine if I added some element in the list in with the help of for loop but not with promise.