|
| 1 | +import { Component, OnInit } from '@angular/core'; |
| 2 | +import { Chats, Users } from 'api/collections'; |
| 3 | +import { User } from 'api/models'; |
| 4 | +import { AlertController, ViewController } from 'ionic-angular'; |
| 5 | +import { MeteorObservable } from 'meteor-rxjs'; |
| 6 | +import * as _ from 'lodash'; |
| 7 | +import { Observable, Subscription } from 'rxjs'; |
| 8 | + |
| 9 | +@Component({ |
| 10 | + selector: 'new-chat', |
| 11 | + templateUrl: 'new-chat.html' |
| 12 | +}) |
| 13 | +export class NewChatComponent implements OnInit { |
| 14 | + senderId: string; |
| 15 | + users: Observable<User[]>; |
| 16 | + usersSubscription: Subscription; |
| 17 | + |
| 18 | + constructor( |
| 19 | + private alertCtrl: AlertController, |
| 20 | + private viewCtrl: ViewController |
| 21 | + ) { |
| 22 | + this.senderId = Meteor.userId(); |
| 23 | + } |
| 24 | + |
| 25 | + ngOnInit() { |
| 26 | + this.loadUsers(); |
| 27 | + } |
| 28 | + |
| 29 | + addChat(user): void { |
| 30 | + MeteorObservable.call('addChat', user._id).subscribe({ |
| 31 | + next: () => { |
| 32 | + this.viewCtrl.dismiss(); |
| 33 | + }, |
| 34 | + error: (e: Error) => { |
| 35 | + this.viewCtrl.dismiss().then(() => { |
| 36 | + this.handleError(e); |
| 37 | + }); |
| 38 | + } |
| 39 | + }); |
| 40 | + } |
| 41 | + |
| 42 | + loadUsers(): void { |
| 43 | + this.users = this.findUsers(); |
| 44 | + } |
| 45 | + |
| 46 | + findUsers(): Observable<User[]> { |
| 47 | + // Find all belonging chats |
| 48 | + return Chats.find({ |
| 49 | + memberIds: this.senderId |
| 50 | + }, { |
| 51 | + fields: { |
| 52 | + memberIds: 1 |
| 53 | + } |
| 54 | + }) |
| 55 | + // Invoke merge-map with an empty array in case no chat found |
| 56 | + .startWith([]) |
| 57 | + .mergeMap((chats) => { |
| 58 | + // Get all userIDs who we're chatting with |
| 59 | + const receiverIds = _.chain(chats) |
| 60 | + .map('memberIds') |
| 61 | + .flatten() |
| 62 | + .concat(this.senderId) |
| 63 | + .value(); |
| 64 | + |
| 65 | + // Find all users which are not in belonging chats |
| 66 | + return Users.find({ |
| 67 | + _id: { $nin: receiverIds } |
| 68 | + }) |
| 69 | + // Invoke map with an empty array in case no user found |
| 70 | + .startWith([]); |
| 71 | + }); |
| 72 | + } |
| 73 | + |
| 74 | + handleError(e: Error): void { |
| 75 | + console.error(e); |
| 76 | + |
| 77 | + const alert = this.alertCtrl.create({ |
| 78 | + buttons: ['OK'], |
| 79 | + message: e.message, |
| 80 | + title: 'Oops!' |
| 81 | + }); |
| 82 | + |
| 83 | + alert.present(); |
| 84 | + } |
| 85 | +} |
0 commit comments