Permalink
Browse files

Step 8.13: Implement chats with with real data

  • Loading branch information...
dotansimha authored and darkbasic committed Jan 24, 2017
1 parent e939ef1 commit 45b40a9110a8642e4e07e5db264b78f553cd38c6
Showing with 60 additions and 18 deletions.
  1. +60 −18 src/pages/chats/chats.ts
View
@@ -1,8 +1,9 @@
import { Component, OnInit } from '@angular/core';
import { Chats, Messages } from 'api/collections';
import { Chat } from 'api/models';
import { Chats, Messages, Users } from 'api/collections';
import { Chat, Message } from 'api/models';
import { NavController, PopoverController, ModalController } from 'ionic-angular';
import { Observable } from 'rxjs';
import { MeteorObservable } from 'meteor-rxjs';
import { Observable, Subscriber } from 'rxjs';
import { MessagesPage } from '../messages/messages';
import { ChatsOptionsComponent } from './chats-options';
import { NewChatComponent } from './new-chat';
@@ -12,11 +13,13 @@ import { NewChatComponent } from './new-chat';
})
export class ChatsPage implements OnInit {
chats;
senderId: string;
constructor(
private navCtrl: NavController,
private popoverCtrl: PopoverController,
private modalCtrl: ModalController) {
this.senderId = Meteor.userId();
}
addChat(): void {
@@ -25,23 +28,62 @@ export class ChatsPage implements OnInit {
}
ngOnInit() {
this.chats = Chats
.find({})
.mergeMap((chats: Chat[]) =>
Observable.combineLatest(
...chats.map((chat: Chat) =>
Messages
.find({chatId: chat._id})
.startWith(null)
.map(messages => {
if (messages) chat.lastMessage = messages[0];
return chat;
})
)
)
).zone();
this.chats = this.findChats();
}
findChats(): Observable<Chat[]> {
// Find chats and transform them
return Chats.find().map(chats => {
chats.forEach(chat => {
chat.title = '';
chat.picture = '';
const receiverId = chat.memberIds.find(memberId => memberId !== this.senderId);
const receiver = Users.findOne(receiverId);
if (receiver) {
chat.title = receiver.profile.name;
chat.picture = receiver.profile.picture;
}
// This will make the last message reactive
this.findLastChatMessage(chat._id).subscribe((message) => {
chat.lastMessage = message;
});
});
return chats;
});
}
findLastChatMessage(chatId: string): Observable<Message> {
return Observable.create((observer: Subscriber<Message>) => {
const chatExists = () => !!Chats.findOne(chatId);
// Re-compute until chat is removed
MeteorObservable.autorun().takeWhile(chatExists).subscribe(() => {
Messages.find({ chatId }, {
sort: { createdAt: -1 }
}).subscribe({
next: (messages) => {
// Invoke subscription with the last message found
if (!messages.length) {
return;
}
const lastMessage = messages[0];
observer.next(lastMessage);
},
error: (e) => {
observer.error(e);
},
complete: () => {
observer.complete();
}
});
});
});
}
showMessages(chat): void {
this.navCtrl.push(MessagesPage, {chat});

0 comments on commit 45b40a9

Please sign in to comment.