From 94ec41a7f08c312fb0fb2253c7a92f25e6ad4db9 Mon Sep 17 00:00:00 2001 From: dotansimha Date: Tue, 24 Jan 2017 17:51:45 +0200 Subject: [PATCH] Step 8.4: Added new chat component --- src/pages/chats/new-chat.ts | 85 +++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 src/pages/chats/new-chat.ts diff --git a/src/pages/chats/new-chat.ts b/src/pages/chats/new-chat.ts new file mode 100644 index 000000000..701abf987 --- /dev/null +++ b/src/pages/chats/new-chat.ts @@ -0,0 +1,85 @@ +import { Component, OnInit } from '@angular/core'; +import { Chats, Users } from 'api/collections'; +import { User } from 'api/models'; +import { AlertController, ViewController } from 'ionic-angular'; +import { MeteorObservable } from 'meteor-rxjs'; +import { _ } from 'meteor/underscore'; +import { Observable, Subscription } from 'rxjs'; + +@Component({ + selector: 'new-chat', + templateUrl: 'new-chat.html' +}) +export class NewChatComponent implements OnInit { + senderId: string; + users: Observable; + usersSubscription: Subscription; + + constructor( + private alertCtrl: AlertController, + private viewCtrl: ViewController + ) { + this.senderId = Meteor.userId(); + } + + ngOnInit() { + this.loadUsers(); + } + + addChat(user): void { + MeteorObservable.call('addChat', user._id).subscribe({ + next: () => { + this.viewCtrl.dismiss(); + }, + error: (e: Error) => { + this.viewCtrl.dismiss().then(() => { + this.handleError(e); + }); + } + }); + } + + loadUsers(): void { + this.users = this.findUsers(); + } + + findUsers(): Observable { + // Find all belonging chats + return Chats.find({ + memberIds: this.senderId + }, { + fields: { + memberIds: 1 + } + }) + // Invoke merge-map with an empty array in case no chat found + .startWith([]) + .mergeMap((chats) => { + // Get all userIDs who we're chatting with + const receiverIds = _.chain(chats) + .pluck('memberIds') + .flatten() + .concat(this.senderId) + .value(); + + // Find all users which are not in belonging chats + return Users.find({ + _id: { $nin: receiverIds } + }) + // Invoke map with an empty array in case no user found + .startWith([]); + }); + } + + handleError(e: Error): void { + console.error(e); + + const alert = this.alertCtrl.create({ + buttons: ['OK'], + message: e.message, + title: 'Oops!' + }); + + alert.present(); + } +}