Skip to content

Instantly share code, notes, and snippets.

@mozhn
Created April 26, 2021 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mozhn/af142877c4d5efd83ba33ff0845bbd0d to your computer and use it in GitHub Desktop.
Save mozhn/af142877c4d5efd83ba33ff0845bbd0d to your computer and use it in GitHub Desktop.
// The part to run when the chat page is first opened. (ionViewDidEnter or ngOnInit)
public async initMessages(): Promise<Message[]> {
const result = await this.fireStore.collection('messages').ref
.orderBy('date', 'desc')
.limit(20).get();
return result.docs.map((value) => {
return {
id: value.id,
...value.data() as Message
};
});
}
// The function that will notify us when a new message arrives, has been deleted or edited.
public messageListener(type: firebase.firestore.DocumentChangeType) {
return this.fireStore.collection('messages', (query) =>
query.orderBy('date')
).stateChanges([type]);
}
// Examples:
const newMessageSub = this.messageListener('added')
.subscribe(async (value) => {
this.messages = this.messages.concat([{
id: value[0].payload.doc.id,
...value[0].payload.doc.data() as Message
}]);
this.content.scrollToBottom(200);
});
const updateMessageSub = this.messageListener('modified')
.subscribe((value) => {
const doc = value[0].payload.doc;
const index = this.messages.findIndex((query) => query.id === doc.id);
this.messages[index] = {
...doc.data() as Message,
id: doc.id
};
});
const removeMessageSub = this.messageListener('removed')
.subscribe((value) => {
const doc = value[0].payload.doc;
const index = this.messages.findIndex((query) => query.id === doc.id);
this.messages.splice(index, 1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment