Fork me on GitHub

WhatsApp Clone with Meteor and Ionic 2 CLI

Socially Merge Version (Last Update: 2017-02-01)

Chats Creation & Removal

Note: If you skipped ahead to this section, click here to download a zip of the tutorial at this point.

Our next step is about adding the ability to create new chats. We have the ChatsPage and the authentication system, but we need to hook them up some how. Let's define the initial User schema which will be used to retrieve its relevant information in our application:

8.1 Added user model api/server/models.ts
25
26
27
28
29
30
31
  type?: MessageType
  ownership?: string;
}
 
export interface User extends Meteor.User {
  profile?: Profile;
}

Meteor comes with a built-in users collection, defined as Meteor.users, but since we're using Observables vastly, we will wrap our collection with one:

8.2 Wrap Meteor users collection api/server/collections/users.ts
1
2
3
4
5
import { MongoObservable } from 'meteor-rxjs';
import { Meteor } from 'meteor/meteor';
import { User } from '../models';
 
export const Users = MongoObservable.fromExisting<User>(Meteor.users);

For accessibility, we're gonna export the collection from the index file as well:

8.3 Export users collection form index file api/server/collections/index.ts
1
2
3
export * from './chats';
export * from './messages';
export * from './users';

Chats Creation

We will be using Ionic's modal dialog to show the chat creation view. The first thing we're gonna do would be implementing the component itself, along with its view and stylesheet:

8.4 Added new chat component src/pages/chats/new-chat.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
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<User[]>;
  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<User[]> {
    // 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();
  }
}
8.5 Added new chat template src/pages/chats/new-chat.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<ion-header>
  <ion-toolbar color="whatsapp">
    <ion-title>New Chat</ion-title>
 
    <ion-buttons left>
      <button ion-button class="dismiss-button" (click)="viewCtrl.dismiss()"><ion-icon name="close"></ion-icon></button>
    </ion-buttons>
 
    <ion-buttons end>
      <button ion-button class="search-button"><ion-icon name="search"></ion-icon></button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>
 
<ion-content class="new-chat">
  <ion-list class="users">
    <button ion-item *ngFor="let user of users | async" class="user" (click)="addChat(user)">
      <img class="user-picture" [src]="user.profile.picture">
      <h2 class="user-name">{{user.profile.name}}</h2>
    </button>
  </ion-list>
</ion-content>
8.6 Added new chat styles src/pages/chats/new-chat.scss
1
2
3
4
5
6
7
8
9
10
11
12
13
14
.new-chat {
  .user-picture {
    border-radius: 50%;
    width: 50px;
    float: left;
  }
 
  .user-name {
    margin-left: 20px;
    margin-top: 25px;
    transform: translate(0, -50%);
    float: left;
  }
}

The dialog should contain a list of all the users whose chat does not exist yet. Once we click on one of these users we should be demoted to the chats view with the new chat we've just created.

The dialog should be revealed whenever we click on one of the options in the options pop-over, therefore, we will implement the necessary handler:

8.7 Added addChat method src/pages/chats/chats.ts
1
2
3
4
5
6
7
8
9
10
11
 
15
16
17
18
19
20
21
22
23
24
25
26
27
 
42
43
44
45
46
47
48
import { Component, OnInit } from '@angular/core';
import { Chats, Messages } from 'api/collections';
import { Chat } from 'api/models';
import { NavController, PopoverController, ModalController } from 'ionic-angular';
import { Observable } from 'rxjs';
import { MessagesPage } from '../messages/messages';
import { ChatsOptionsComponent } from './chats-options';
import { NewChatComponent } from './new-chat';
 
@Component({
  templateUrl: 'chats.html'
...some lines skipped...
 
  constructor(
    private navCtrl: NavController,
    private popoverCtrl: PopoverController,
    private modalCtrl: ModalController) {
  }
 
  addChat(): void {
    const modal = this.modalCtrl.create(NewChatComponent);
    modal.present();
  }
 
  ngOnInit() {
...some lines skipped...
      ).zone();
  }
 
 
  showMessages(chat): void {
    this.navCtrl.push(MessagesPage, {chat});
  }

And bind it to the click event:

8.8 Bind click event to new chat modal src/pages/chats/chats.html
4
5
6
7
8
9
10
      Chats
    </ion-title>
    <ion-buttons end>
      <button ion-button icon-only class="add-chat-button" (click)="addChat()">
        <ion-icon name="person-add"></ion-icon>
      </button>
      <button ion-button icon-only class="options-button" (click)="showOptions()">

We will import the newly created component in the app's NgModule as well, so it can be recognized properly:

8.9 Import new chat component src/app/app.module.ts
2
3
4
5
6
7
8
 
19
20
21
22
23
24
25
26
 
34
35
36
37
38
39
40
41
import { MomentModule } from 'angular2-moment';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { ChatsPage } from '../pages/chats/chats';
import { NewChatComponent } from '../pages/chats/new-chat';
import { ChatsOptionsComponent } from '../pages/chats/chats-options';
import { LoginPage } from '../pages/login/login';
import { MessagesPage } from '../pages/messages/messages';
...some lines skipped...
    LoginPage,
    VerificationPage,
    ProfilePage,
    ChatsOptionsComponent,
    NewChatComponent
  ],
  imports: [
    IonicModule.forRoot(MyApp),
...some lines skipped...
    LoginPage,
    VerificationPage,
    ProfilePage,
    ChatsOptionsComponent,
    NewChatComponent
  ],
  providers: [
    {provide: ErrorHandler, useClass: IonicErrorHandler},

We're also required to implement the appropriate Meteor method which will be the actually handler for feeding our data-base with newly created chats:

8.10 Implement addChat method api/server/methods.ts
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
});
 
Meteor.methods({
  addChat(receiverId: string): void {
    if (!this.userId) {
      throw new Meteor.Error('unauthorized',
        'User must be logged-in to create a new chat');
    }
 
    check(receiverId, nonEmptyString);
 
    if (receiverId === this.userId) {
      throw new Meteor.Error('illegal-receiver',
        'Receiver must be different than the current logged in user');
    }
 
    const chatExists = !!Chats.collection.find({
      memberIds: { $all: [this.userId, receiverId] }
    }).count();
 
    if (chatExists) {
      throw new Meteor.Error('chat-exists',
        'Chat already exists');
    }
 
    const chat = {
      memberIds: [this.userId, receiverId]
    };
 
    Chats.insert(chat);
  },
  updateProfile(profile: Profile): void {
    if (!this.userId) throw new Meteor.Error('unauthorized',
      'User must be logged-in to create a new chat');

As you can see, a chat is inserted with an additional memberIds field. Whenever we have such a change we should update the model's schema accordingly, in this case we're talking about adding the memberIds field, like so:

8.11 Add memberIds field api/server/models.ts
14
15
16
17
18
19
20
  title?: string;
  picture?: string;
  lastMessage?: Message;
  memberIds?: string[];
}
 
export interface Message {

Thanks to our new-chat dialog, we can create chats dynamically with no need in initial fabrication. Let's replace the chats fabrication with users fabrication in the Meteor server:

8.12 Create real user accounts api/server/main.ts
4
5
6
7
8
9
10
 
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
import * as moment from 'moment';
import { MessageType } from './models';
import { Accounts } from 'meteor/accounts-base';
import { Users } from './collections/users';
 
Meteor.startup(() => {
  if (Meteor.settings) {
...some lines skipped...
    SMS.twilio = Meteor.settings['twilio'];
  }
 
  if (Users.collection.find().count() > 0) {
    return;
  }
 
  Accounts.createUserWithPhone({
    phone: '+972540000001',
    profile: {
      name: 'Ethan Gonzalez',
      picture: 'https://randomuser.me/api/portraits/men/1.jpg'
    }
  });
 
  Accounts.createUserWithPhone({
    phone: '+972540000002',
    profile: {
      name: 'Bryan Wallace',
      picture: 'https://randomuser.me/api/portraits/lego/1.jpg'
    }
  });
 
  Accounts.createUserWithPhone({
    phone: '+972540000003',
    profile: {
      name: 'Avery Stewart',
      picture: 'https://randomuser.me/api/portraits/women/1.jpg'
    }
  });
 
  Accounts.createUserWithPhone({
    phone: '+972540000004',
    profile: {
      name: 'Katie Peterson',
      picture: 'https://randomuser.me/api/portraits/women/2.jpg'
    }
  });
 
  Accounts.createUserWithPhone({
    phone: '+972540000005',
    profile: {
      name: 'Ray Edwards',
      picture: 'https://randomuser.me/api/portraits/men/2.jpg'
    }
  });
});

Since we've changed the data fabrication method, the chat's title and picture are not hard-coded anymore, therefore, any additional data should be fetched in the components themselves:

8.13 Implement chats with with real data src/pages/chats/chats.ts
1
2
3
4
5
6
7
8
9
 
13
14
15
16
17
18
19
20
21
22
23
24
25
 
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
85
86
87
88
89
import { Component, OnInit } from '@angular/core';
import { Chats, Messages, Users } from 'api/collections';
import { Chat, Message } from 'api/models';
import { NavController, PopoverController, ModalController } from 'ionic-angular';
import { MeteorObservable } from 'meteor-rxjs';
import { Observable, Subscriber } from 'rxjs';
import { MessagesPage } from '../messages/messages';
import { ChatsOptionsComponent } from './chats-options';
import { NewChatComponent } from './new-chat';
...some lines skipped...
})
export class ChatsPage implements OnInit {
  chats;
  senderId: string;
 
  constructor(
    private navCtrl: NavController,
    private popoverCtrl: PopoverController,
    private modalCtrl: ModalController) {
    this.senderId = Meteor.userId();
  }
 
  addChat(): void {
...some lines skipped...
  }
 
  ngOnInit() {
    this.chats = this.findChats();
  }
 
  findChats(): Observable<Chat[]> {
    // Find chats and transform them
    return Chats.find().map(chats => {
      chats.forEach(chat => {
        chat.title = '';
        chat.picture = '';
 
        const receiverId = chat.memberIds.find(memberId => memberId !== this.senderId);
        const receiver = Users.findOne(receiverId);
 
        if (receiver) {
          chat.title = receiver.profile.name;
          chat.picture = receiver.profile.picture;
        }
 
        // This will make the last message reactive
        this.findLastChatMessage(chat._id).subscribe((message) => {
          chat.lastMessage = message;
        });
      });
 
      return chats;
    });
  }
 
  findLastChatMessage(chatId: string): Observable<Message> {
    return Observable.create((observer: Subscriber<Message>) => {
      const chatExists = () => !!Chats.findOne(chatId);
 
      // Re-compute until chat is removed
      MeteorObservable.autorun().takeWhile(chatExists).subscribe(() => {
        Messages.find({ chatId }, {
          sort: { createdAt: -1 }
        }).subscribe({
          next: (messages) => {
            // Invoke subscription with the last message found
            if (!messages.length) {
              return;
            }
 
            const lastMessage = messages[0];
            observer.next(lastMessage);
          },
          error: (e) => {
            observer.error(e);
          },
          complete: () => {
            observer.complete();
          }
        });
      });
    });
  }
 
  showMessages(chat): void {
    this.navCtrl.push(MessagesPage, {chat});

Now we want our changes to take effect. We will reset the database so next time we run our Meteor server the users will be fabricated. To reset the database, first make sure the Meteor server is stopped , and then type the following command:

api$ meteor reset

Now, as soon as you start the server, new users should be fabricated and inserted into the database:

$ npm run api