I have a Firebase service provider function returning a set of data by a promise object:
getPreviousChats(groupKey: string, offset: string): Promise<any> {
return new Promise((resolve, reject) => {
// let previousChats: Array<any> = [];
let previousChats: any[] = [];
const chatRef = this.chatsRef.child(groupKey).orderByKey().endAt(offset).limitToLast(5);
chatRef.once('value', snapshot => {
snapshot.forEach(childSnapshot => {
previousChats.push({
id: childSnapshot.key,
message: childSnapshot.val().message,
createTime: childSnapshot.val().createTime
});
return false; // forEach returns boolean
});
});
resolve(previousChats);
});
}
Meanwhile, an Ionic page function calls getPreviousChats()
to retrieve previous chat data and add it to current page layout by unshift()
:
loadPreviousChats(refresher) {
this.dataService.getPreviousChats(this.groupKey, this.chats[0].id).then(data => {
this.chats.unshift(data);
}, (error) => {
console.log('loadPreviousChats error: ', JSON.stringify(error));
});
setTimeout(() => {
console.log('Async operation has ended');
refresher.complete();
}, 1000);
}
Unfortunately, somehow this.chats.unshift(data);
inserts the data
in front of current this.chats
array with an extra layer of array:
this.chats: Array[6]
0: Array[5]
0: Object
1: Object
2: Object
3: Object
4: Object
length: 5
__proto__: Array[0]
1: Object
2: Object
3: Object
4: Object
5: Object
length: 6
__proto__: Array[0]
So, what am I missing here?