/
chats.component.ts
84 lines (72 loc) · 2.44 KB
/
chats.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import {Component, OnInit} from "@angular/core";
import template from "./chats.component.html"
import {Observable} from "rxjs";
import {Meteor} from 'meteor/meteor';
import {MeteorObservable} from 'meteor-rxjs';
import {Chat} from "../../../../both/models/chat.model";
import * as moment from "moment";
import style from "./chats.component.scss";
import {Chats} from "../../../../both/collections/chats.collection";
import {Message} from "../../../../both/models/message.model";
import {Messages} from "../../../../both/collections/messages.collection";
import {NavController, PopoverController, ModalController} from "ionic-angular";
import {MessagesPage} from "../chat/messages-page.component";
import {ChatsOptionsComponent} from '../chats/chats-options.component';
import {NewChatComponent} from './new-chat.component';
@Component({
selector: "chats",
template,
styles: [
style
]
})
export class ChatsComponent implements OnInit {
chats: Observable<Chat[]>;
senderId: string;
constructor(
private navCtrl: NavController,
private popoverCtrl: PopoverController,
private modalCtrl: ModalController
) {}
ngOnInit() {
this.senderId = Meteor.userId();
MeteorObservable.subscribe('chats').subscribe(() => {
MeteorObservable.autorun().subscribe(() => {
this.chats = Chats
.find({})
.mergeMap<Chat[]>(chats =>
Observable.combineLatest(
...chats.map(chat =>
Messages.find({ chatId: chat._id }, { sort: { createdAt: -1 }, limit: 1 })
.startWith(null)
.map(messages => {
if (messages) chat.lastMessage = messages[0];
return chat;
})
)
)
).map(chats => {
chats.forEach(chat => {
const receiver = Meteor.users.findOne(chat.memberIds.find(memberId => memberId !== this.senderId))
chat.title = receiver.profile.name;
chat.picture = receiver.profile.picture;
});
return chats;
}).zone();
});
});
}
addChat(): void {
const modal = this.modalCtrl.create(NewChatComponent);
modal.present();
}
showOptions(): void {
const popover = this.popoverCtrl.create(ChatsOptionsComponent, {}, {
cssClass: 'options-popover'
});
popover.present();
}
showMessages(chat): void {
this.navCtrl.push(MessagesPage, {chat});
}
}