From 5f43d6d8b2317956774d1ee75c4cf2680a992557 Mon Sep 17 00:00:00 2001 From: Dotan Simha Date: Thu, 3 Nov 2016 18:15:15 +0200 Subject: [PATCH] Step 3.16: Added the chats with the last message using RxJS operators --- src/pages/chats/chats.ts | 74 ++++++++++++---------------------------- 1 file changed, 21 insertions(+), 53 deletions(-) diff --git a/src/pages/chats/chats.ts b/src/pages/chats/chats.ts index 1901c1038..3c8d37298 100644 --- a/src/pages/chats/chats.ts +++ b/src/pages/chats/chats.ts @@ -1,66 +1,34 @@ -import * as moment from 'moment'; -import { Component } from '@angular/core'; +import { Component, OnInit } from '@angular/core'; import { Observable } from "rxjs"; import { Chat } from "api/models/whatsapp-models"; +import { Chats, Messages } from "api/collections/whatsapp-collections"; @Component({ templateUrl: 'chats.html' }) -export class ChatsPage { - chats: Observable; +export class ChatsPage implements OnInit { + chats; constructor() { - this.chats = this.findChats(); + } - private findChats(): Observable { - return Observable.of([ - { - _id: '0', - title: 'Ethan Gonzalez', - picture: 'https://randomuser.me/api/portraits/thumb/men/1.jpg', - lastMessage: { - content: 'You on your way?', - createdAt: moment().subtract(1, 'hours').toDate() - } - }, - { - _id: '1', - title: 'Bryan Wallace', - picture: 'https://randomuser.me/api/portraits/thumb/lego/1.jpg', - lastMessage: { - content: 'Hey, it\'s me', - createdAt: moment().subtract(2, 'hours').toDate() - } - }, - { - _id: '2', - title: 'Avery Stewart', - picture: 'https://randomuser.me/api/portraits/thumb/women/1.jpg', - lastMessage: { - content: 'I should buy a boat', - createdAt: moment().subtract(1, 'days').toDate() - } - }, - { - _id: '3', - title: 'Katie Peterson', - picture: 'https://randomuser.me/api/portraits/thumb/women/2.jpg', - lastMessage: { - content: 'Look at my mukluks!', - createdAt: moment().subtract(4, 'days').toDate() - } - }, - { - _id: '4', - title: 'Ray Edwards', - picture: 'https://randomuser.me/api/portraits/thumb/men/2.jpg', - lastMessage: { - content: 'This is wicked good ice cream.', - createdAt: moment().subtract(2, 'weeks').toDate() - } - } - ]); + 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(); } removeChat(chat: Chat): void {