Fork me on GitHub

WhatsApp Clone with Ionic 2 and Meteor CLI

Socially Merge Version (Last Update: 14.02.2017)

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 imports/models.ts
1
2
3
4
5
 
26
27
28
29
30
31
32
33
import { Meteor } from 'meteor/meteor';
 
export const DEFAULT_PICTURE_URL = '/assets/default-profile-pic.svg';
 
export interface Profile {
...some lines skipped...
  createdAt?: Date;
  ownership?: string;
  type?: MessageType;
}
 
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 imports/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 imports/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 Add new-chat component client/imports/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 [email protected]/core';
import { AlertController, ViewController } from 'ionic-angular';
import { MeteorObservable } from 'meteor-rxjs';
import { _ } from 'meteor/underscore';
import { Observable, Subscription } from 'rxjs';
import { Chats, Users } from '../../../../imports/collections';
import { User } from '../../../../imports/models';
import template from './new-chat.html';
 
@Component({
  template
})
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 Add new-chat template client/imports/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>
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;
  }
}
8.6 Add new-chat style client/main.scss
6
7
8
9
10
11
12
 
// Pages
@import "imports/pages/chats/chats";
@import "imports/pages/chats/new-chat";
@import "imports/pages/chats/chats-options";
@import "imports/pages/login/login";
@import "imports/pages/messages/messages";

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 Add addChat method client/imports/pages/chats/chats.ts
1
2
3
4
5
 
7
8
9
10
11
12
13
 
17
18
19
20
21
22
23
24
 
39
40
41
42
43
44
45
46
47
48
49
import { Component, OnInit } from [email protected]/core';
import { NavController, PopoverController, ModalController } from 'ionic-angular';
import * as Moment from 'moment';
import { Observable } from 'rxjs';
import { Chats, Messages } from '../../../../imports/collections';
...some lines skipped...
import { ChatsOptionsComponent } from './chats-options';
import { MessagesPage } from '../messages/messages';
import template from './chats.html';
import { NewChatComponent } from './new-chat';
 
@Component({
  template
...some lines skipped...
 
  constructor(
    private navCtrl: NavController,
    private popoverCtrl: PopoverController,
    private modalCtrl: ModalController) {
  }
 
  ngOnInit() {
...some lines skipped...
      ).zone();
  }
 
  addChat(): void {
    const modal = this.modalCtrl.create(NewChatComponent);
    modal.present();
  }
 
  showMessages(chat): void {
    this.navCtrl.push(MessagesPage, {chat});
  }

And bind it to the click event:

8.8 Bind click event to new chat modal client/imports/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 client/imports/app/app.module.ts
3
4
5
6
7
8
9
 
19
20
21
22
23
24
25
26
 
34
35
36
37
38
39
40
41
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { ChatsPage } from '../pages/chats/chats'
import { ChatsOptionsComponent } from '../pages/chats/chats-options';
import { NewChatComponent } from '../pages/chats/new-chat';
import { LoginPage } from '../pages/login/login';
import { MessagesPage } from '../pages/messages/messages';
import { ProfilePage } from '../pages/profile/profile';
...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 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
43
});
 
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 imports/models.ts
16
17
18
19
20
21
22
  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 server/main.ts
1
2
3
4
5
6
7
 
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
import { Accounts } from 'meteor/accounts-base';
import { Meteor } from 'meteor/meteor';
import * as Moment from 'moment';
import { Chats, Messages, Users } from '../imports/collections';
import { MessageType } from '../imports/models';
 
Meteor.startup(() => {
...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 client/imports/pages/chats/chats.ts
1
2
3
4
5
6
7
8
9
10
 
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 
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
90
91
92
import { Component, OnInit } from [email protected]/core';
import { NavController, PopoverController, ModalController } from 'ionic-angular';
import { MeteorObservable } from 'meteor-rxjs';
import * as Moment from 'moment';
import { Observable, Subscriber } from 'rxjs';
import { Chats, Messages, Users } from '../../../../imports/collections';
import { Chat, Message, MessageType } from '../../../../imports/models';
import { ChatsOptionsComponent } from './chats-options';
import { MessagesPage } from '../messages/messages';
import template from './chats.html';
...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();
  }
 
  ngOnInit() {
    this.chats = this.findChats();
  }
 
  addChat(): void {
...some lines skipped...
    modal.present();
  }
 
  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:

$ meteor reset

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

$ npm run start

{{{nav_step prev_ref="https://angular-meteor.com/tutorials/whatsapp2/meteor/authentication" next_ref="https://angular-meteor.com/tutorials/whatsapp2/meteor/privacy"}}}