Skip to content

Commit

Permalink
Step 7.17: Subscribe to 'chats'
Browse files Browse the repository at this point in the history
  • Loading branch information
DAB0mB committed Dec 24, 2016
1 parent d0fc1fb commit e534c8f
Showing 1 changed file with 38 additions and 28 deletions.
66 changes: 38 additions & 28 deletions src/pages/chats/chats.ts
Expand Up @@ -6,6 +6,7 @@ import { NavController, PopoverController, ModalController, AlertController } fr
import { MessagesPage } from "../messages/messages";
import { ChatsOptionsComponent } from "../chat-options/chat-options";
import { NewChatComponent } from "../new-chat/new-chat";
import { MeteorObservable } from 'meteor-rxjs';

@Component({
templateUrl: 'chats.html'
Expand All @@ -24,34 +25,43 @@ export class ChatsPage implements OnInit {
ngOnInit() {
this.senderId = Meteor.userId();

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;
})
)
)
).map(chats => {
chats.forEach(chat => {
chat.title = '';
chat.picture = '';

const receiver = Users.findOne(chat.memberIds.find(memberId => memberId !== this.senderId));
if (!receiver) return;

chat.title = receiver.profile.name;
chat.picture = receiver.profile.picture;
});

return chats;
}).zone();
MeteorObservable.subscribe('chats').subscribe(() => {
MeteorObservable.autorun().subscribe(() => {
if (this.chats) {
this.chats.unsubscribe();
this.chats = undefined;
}

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;
})
)
)
).map(chats => {
chats.forEach(chat => {
chat.title = '';
chat.picture = '';

const receiver = Users.findOne(chat.memberIds.find(memberId => memberId !== this.senderId));
if (!receiver) return;

chat.title = receiver.profile.name;
chat.picture = receiver.profile.picture;
});

return chats;
}).zone();
});
});
}

addChat(): void {
Expand Down

0 comments on commit e534c8f

Please sign in to comment.