Skip to content

Commit 9e52e87

Browse files
dotansimhadarkbasic
authored andcommitted
Step 4.20: Use server side data
1 parent 246c3dd commit 9e52e87

File tree

1 file changed

+21
-59
lines changed

1 file changed

+21
-59
lines changed

src/pages/chats/chats.ts

Lines changed: 21 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,71 +1,33 @@
1-
import { Component } from '@angular/core';
1+
import { Component, OnInit } from '@angular/core';
2+
import { Chats, Messages } from 'api/collections';
3+
import { Chat } from 'api/models';
24
import { Observable } from 'rxjs';
3-
import * as moment from 'moment';
4-
import { Chat, MessageType } from 'api/models';
55

66
@Component({
77
templateUrl: 'chats.html'
88
})
9-
export class ChatsPage {
10-
chats: Observable<Chat[]>;
9+
export class ChatsPage implements OnInit {
10+
chats;
1111

1212
constructor() {
13-
this.chats = this.findChats();
1413
}
1514

16-
private findChats(): Observable<Chat[]> {
17-
return Observable.of([
18-
{
19-
_id: '0',
20-
title: 'Ethan Gonzalez',
21-
picture: 'https://randomuser.me/api/portraits/thumb/men/1.jpg',
22-
lastMessage: {
23-
content: 'You on your way?',
24-
createdAt: moment().subtract(1, 'hours').toDate(),
25-
type: MessageType.TEXT
26-
}
27-
},
28-
{
29-
_id: '1',
30-
title: 'Bryan Wallace',
31-
picture: 'https://randomuser.me/api/portraits/thumb/lego/1.jpg',
32-
lastMessage: {
33-
content: 'Hey, it\'s me',
34-
createdAt: moment().subtract(2, 'hours').toDate(),
35-
type: MessageType.TEXT
36-
}
37-
},
38-
{
39-
_id: '2',
40-
title: 'Avery Stewart',
41-
picture: 'https://randomuser.me/api/portraits/thumb/women/1.jpg',
42-
lastMessage: {
43-
content: 'I should buy a boat',
44-
createdAt: moment().subtract(1, 'days').toDate(),
45-
type: MessageType.TEXT
46-
}
47-
},
48-
{
49-
_id: '3',
50-
title: 'Katie Peterson',
51-
picture: 'https://randomuser.me/api/portraits/thumb/women/2.jpg',
52-
lastMessage: {
53-
content: 'Look at my mukluks!',
54-
createdAt: moment().subtract(4, 'days').toDate(),
55-
type: MessageType.TEXT
56-
}
57-
},
58-
{
59-
_id: '4',
60-
title: 'Ray Edwards',
61-
picture: 'https://randomuser.me/api/portraits/thumb/men/2.jpg',
62-
lastMessage: {
63-
content: 'This is wicked good ice cream.',
64-
createdAt: moment().subtract(2, 'weeks').toDate(),
65-
type: MessageType.TEXT
66-
}
67-
}
68-
]);
15+
ngOnInit() {
16+
this.chats = Chats
17+
.find({})
18+
.mergeMap((chats: Chat[]) =>
19+
Observable.combineLatest(
20+
...chats.map((chat: Chat) =>
21+
Messages
22+
.find({chatId: chat._id})
23+
.startWith(null)
24+
.map(messages => {
25+
if (messages) chat.lastMessage = messages[0];
26+
return chat;
27+
})
28+
)
29+
)
30+
).zone();
6931
}
7032

7133
removeChat(chat: Chat): void {

0 commit comments

Comments
 (0)