-
-
Save mozhn/af142877c4d5efd83ba33ff0845bbd0d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
}; | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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