Fork me on GitHub

WhatsApp Clone with Ionic 2 and Meteor CLI

Socially Merge Version (Last Update: 14.02.2017)

Authentication

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

In this step we will authenticate and identify users in our app.

Before we go ahead and start extending our app, we will add a few packages which will make our lives a bit less complex when it comes to authentication and users management.

First we will update our Meteor project and add a couple of packages: accounts-base and accounts-phone. These will give us the ability to verify a user using an SMS code:

$ meteor add accounts-base
$ meteor add npm-bcrypt
$ meteor add mys:accounts-phone

For the sake of debugging we gonna write an authentication settings file (private/settings.json) which might make our life easier, but once you're in production mode you shouldn't use this configuration:

7.2 Add accounts-phone settings private/settings.json
1
2
3
4
5
6
7
8
{
  "accounts-phone": {
    "verificationWaitTime": 0,
    "verificationRetriesWaitTime": 0,
    "adminPhoneNumbers": ["+9721234567", "+97212345678", "+97212345679"],
    "phoneVerificationMasterCode": "1234"
  }
}

Now anytime we run our app we should provide it with a settings.json:

$ meteor run --settings private/settings.json

To make it easier, we're gonna edit the start script defined in the package.json by appending the following:

7.3 Updated NPM script package.json
2
3
4
5
6
7
8
  "name": "Ionic2-MeteorCLI-WhatsApp",
  "private": true,
  "scripts": {
    "start": "meteor run --settings private/settings.json"
  },
  "dependencies": {
    "@angular/common": "2.2.1",

NOTE: If you would like to test the verification with a real phone number, accounts-phone provides an easy access for twilio's API, for more information see accounts-phone's repo.

We will now apply the settings file we've just created so it can actually take effect:

7.4 Added meteor accounts config server/main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { Accounts } from 'meteor/accounts-base';
import { Meteor } from 'meteor/meteor';
import * as Moment from 'moment';
import { Chats, Messages } from '../imports/collections';
import { MessageType } from '../imports/models';
 
Meteor.startup(() => {
  if (Meteor.settings) {
    Object.assign(Accounts._options, Meteor.settings['accounts-phone']);
    SMS.twilio = Meteor.settings['twilio'];
  }
 
  if (Chats.find({}).cursor.count() === 0) {
    let chatId;
 

We also need to make sure we have the necessary declaration files for the package we've just added, so the compiler can recognize the new API:

$ meteor npm install --save-dev @types/meteor-accounts-phone

And we will reference from the tsconfig.json like so:

7.6 Updated tsconfig tsconfig.json
18
19
20
21
22
23
24
25
    "noImplicitAny": false,
    "types": [
      "meteor-typings",
      "@types/underscore",
      "@types/meteor-accounts-phone"
    ]
  },
  "include": [

Using Meteor's Accounts System

Now, we will use the Meteor's accounts system in the client. Our first use case would be delaying our app's bootstrap phase, until Meteor's accounts system has done it's initialization.

Meteor's accounts API exposes a method called loggingIn which indicates if the authentication flow is done, which we gonna use before bootstraping our application, to make sure we provide the client with the necessary views which are right to his current state:

7.7 Wait for user if logging in client/main.ts
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import 'reflect-metadata';
 
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { MeteorObservable } from 'meteor-rxjs';
import { Meteor } from 'meteor/meteor';
import { AppModule } from './imports/app/app.module';
 
Meteor.startup(() => {
  const subscription = MeteorObservable.autorun().subscribe(() => {
    if (Meteor.loggingIn()) {
      return;
    }
 
    setTimeout(() => subscription.unsubscribe());
    platformBrowserDynamic().bootstrapModule(AppModule);
  });
});

To make things easier, we're going to organize all authentication related functions into a single service which we're gonna call PhoneService:

7.8 Added phone service client/imports/services/phone.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
import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';
import { Accounts } from 'meteor/accounts-base';
import { Meteor } from 'meteor/meteor';
 
@Injectable()
export class PhoneService {
  constructor(private platform: Platform) {
 
  }
 
  verify(phoneNumber: string): Promise<void> {
    return new Promise<void>((resolve, reject) => {
      Accounts.requestPhoneVerification(phoneNumber, (e: Error) => {
        if (e) {
          return reject(e);
        }
 
        resolve();
      });
    });
  }
 
  login(phoneNumber: string, code: string): Promise<void> {
    return new Promise<void>((resolve, reject) => {
      Accounts.verifyPhone(phoneNumber, code, (e: Error) => {
        if (e) {
          return reject(e);
        }
 
        resolve();
      });
    });
  }
 
  logout(): Promise<void> {
    return new Promise<void>((resolve, reject) => {
      Meteor.logout((e: Error) => {
        if (e) {
          return reject(e);
        }
 
        resolve();
      });
    });
  }
}

And we gonna require it in the app's NgModule so it can be recognized:

7.9 Added phone service to NgModule client/imports/app/app.module.ts
3
4
5
6
7
8
9
 
23
24
25
26
27
28
29
30
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { ChatsPage } from '../pages/chats/chats'
import { MessagesPage } from '../pages/messages/messages';
import { PhoneService } from '../services/phone';
import { MyApp } from './app.component';
 
@NgModule({
...some lines skipped...
    MessagesPage
  ],
  providers: [
    { provide: ErrorHandler, useClass: IonicErrorHandler },
    PhoneService
  ]
})
export class AppModule {}

The PhoneService is not only packed with whatever functionality we need, but it also wraps async callbacks with promises, which has several advantages:

  • A promise is chainable, and provides an easy way to manage an async flow.
  • A promise is wrapped with zone, which means the view will be updated automatically once the callback has been invoked.
  • A promise can interface with an Observable.

UI

For authentication purposes, we gonna create the following flow in our app:

  • login - The initial page in the authentication flow where the user fills up his phone number.
  • verification - Verify a user's phone number by an SMS authentication.
  • profile - Ask a user to pickup its name. Afterwards he will be promoted to the tabs page.

Let's start by creating the LoginComponent. In this component we will request an SMS verification right after a phone number has been entered:

7.10 Add login component client/imports/pages/login/login.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
import { Component } from '@angular/core';
import { Alert, AlertController, NavController } from 'ionic-angular';
import { PhoneService } from '../../services/phone';
import template from './login.html';
 
@Component({
  template
})
export class LoginPage {
  phone = '';
 
  constructor(
    private alertCtrl: AlertController,
    private phoneService: PhoneService,
    private navCtrl: NavController
  ) {}
 
  onInputKeypress({keyCode}: KeyboardEvent): void {
    if (keyCode === 13) {
      this.login();
    }
  }
 
  login(phone: string = this.phone): void {
    const alert = this.alertCtrl.create({
      title: 'Confirm',
      message: `Would you like to proceed with the phone number ${phone}?`,
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel'
        },
        {
          text: 'Yes',
          handler: () => {
            this.handleLogin(alert);
            return false;
          }
        }
      ]
    });
 
    alert.present();
  }
 
  handleLogin(alert: Alert): void {
    alert.dismiss().then(() => {
      return this.phoneService.verify(this.phone);
    })
    .catch((e) => {
      this.handleError(e);
    });
  }
 
  handleError(e: Error): void {
    console.error(e);
 
    const alert = this.alertCtrl.create({
      title: 'Oops!',
      message: e.message,
      buttons: ['OK']
    });
 
    alert.present();
  }
}

In short, once we press the login button, the login method is called and shows an alert dialog to confirm the action (See reference). If an error has occurred, the handlerError method is called and shows an alert dialog with the received error. If everything went as expected the handleLogin method is invoked, which will call the login method in the PhoneService.

Hopefully that the component's logic is clear now, let's move to the template:

7.11 Add login template client/imports/pages/login/login.html
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
<ion-header>
  <ion-navbar color="whatsapp">
    <ion-title>Login</ion-title>
 
    <ion-buttons end>
      <button ion-button class="done-button" (click)="login()">Done</button>
    </ion-buttons>
  </ion-navbar>
</ion-header>
 
<ion-content padding class="login-page-content">
  <div class="instructions">
    <div>
      Please enter your phone number including its country code.
    </div>
    <br>
    <div>
      The messenger will send a one time SMS message to verify your phone number. Carrier SMS charges may apply.
    </div>
  </div>
 
  <ion-item>
    <ion-input [(ngModel)]="phone" (keypress)="onInputKeypress($event)" type="tel" placeholder="Your phone number"></ion-input>
  </ion-item>
</ion-content>

And add some style into it:

7.12 Add login component styles client/imports/pages/login/login.scss
1
2
3
4
5
6
7
8
9
10
11
.login-page-content {
  .instructions {
    text-align: center;
    font-size: medium;
    margin: 50px;
  }
 
  .text-input {
    text-align: center;
  }
}
7.12 Add login component styles client/main.scss
6
7
8
9
10
 
// Pages
@import "imports/pages/chats/chats";
@import "imports/pages/login/login";
@import "imports/pages/messages/messages";

And as usual, newly created components should be imported in the app's module:

7.13 Import login component client/imports/app/app.module.ts
2
3
4
5
6
7
8
 
11
12
13
14
15
16
17
18
 
22
23
24
25
26
27
28
29
import { MomentModule } from 'angular2-moment';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { ChatsPage } from '../pages/chats/chats'
import { LoginPage } from '../pages/login/login';
import { MessagesPage } from '../pages/messages/messages';
import { PhoneService } from '../services/phone';
import { MyApp } from './app.component';
...some lines skipped...
  declarations: [
    MyApp,
    ChatsPage,
    MessagesPage,
    LoginPage
  ],
  imports: [
    IonicModule.forRoot(MyApp),
...some lines skipped...
  entryComponents: [
    MyApp,
    ChatsPage,
    MessagesPage,
    LoginPage
  ],
  providers: [
    { provide: ErrorHandler, useClass: IonicErrorHandler },

We will also need to identify if the user is logged in or not once the app is launched; If so - the user will be promoted directly to the ChatsPage, and if not, he will have to go through the LoginPage first:

7.14 Add user identification in app's main component client/imports/app/app.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { Meteor } from 'meteor/meteor';
import { ChatsPage } from '../pages/chats/chats';
import { LoginPage } from '../pages/login/login';
import template from "./app.html";
 
@Component({
  template
})
export class MyApp {
  rootPage: any;
 
  constructor(platform: Platform) {
    this.rootPage = Meteor.user() ? ChatsPage : LoginPage;
 
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.

Let's proceed and implement the verification page. We will start by creating its component, called VerificationPage. Logic is pretty much the same as in the LoginComponent:

7.15 Added verification component client/imports/pages/verification/verification.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
import { Component, OnInit } from '@angular/core';
import { AlertController, NavController, NavParams } from 'ionic-angular';
import { PhoneService } from '../../services/phone';
import template from './verification.html';
 
@Component({
  template
})
export class VerificationPage implements OnInit {
  code: string = '';
  phone: string;
 
  constructor(
    private alertCtrl: AlertController,
    private navCtrl: NavController,
    private navParams: NavParams,
    private phoneService: PhoneService
  ) {}
 
  ngOnInit() {
    this.phone = this.navParams.get('phone');
  }
 
  onInputKeypress({keyCode}: KeyboardEvent): void {
    if (keyCode === 13) {
      this.verify();
    }
  }
 
  verify(): void {
    this.phoneService.login(this.phone, this.code)
    .catch((e) => {
      this.handleError(e);
    });
  }
 
  handleError(e: Error): void {
    console.error(e);
 
    const alert = this.alertCtrl.create({
      title: 'Oops!',
      message: e.message,
      buttons: ['OK']
    });
 
    alert.present();
  }
}
7.16 Added verification template client/imports/pages/verification/verification.html
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
<ion-header>
  <ion-navbar color="whatsapp">
    <ion-title>Verification</ion-title>
 
    <ion-buttons end>
      <button ion-button class="verify-button" (click)="verify()">Verify</button>
    </ion-buttons>
  </ion-navbar>
</ion-header>
 
<ion-content padding class="verification-page-content">
  <div class="instructions">
    <div>
      An SMS message with the verification code has been sent to {{phone}}.
    </div>
    <br>
    <div>
      To proceed, please enter the 4-digit verification code below.
    </div>
  </div>
 
  <ion-item>
    <ion-input [(ngModel)]="code" (keypress)="onInputKeypress($event)" type="tel" placeholder="Your verification code"></ion-input>
  </ion-item>
</ion-content>
7.17 Added stylesheet for verification component client/imports/pages/verification/verification.scss
1
2
3
4
5
6
7
8
9
10
11
.verification-page-content {
  .instructions {
    text-align: center;
    font-size: medium;
    margin: 50px;
  }
 
  .text-input {
    text-align: center;
  }
}
7.17 Added stylesheet for verification component client/main.scss
7
8
9
10
11
// Pages
@import "imports/pages/chats/chats";
@import "imports/pages/login/login";
@import "imports/pages/messages/messages";
@import "imports/pages/verification/verification";

And add it to the NgModule:

7.18 Import verification component client/imports/app/app.module.ts
4
5
6
7
8
9
10
 
13
14
15
16
17
18
19
20
 
25
26
27
28
29
30
31
32
import { ChatsPage } from '../pages/chats/chats'
import { LoginPage } from '../pages/login/login';
import { MessagesPage } from '../pages/messages/messages';
import { VerificationPage } from '../pages/verification/verification';
import { PhoneService } from '../services/phone';
import { MyApp } from './app.component';
 
...some lines skipped...
    MyApp,
    ChatsPage,
    MessagesPage,
    LoginPage,
    VerificationPage
  ],
  imports: [
    IonicModule.forRoot(MyApp),
...some lines skipped...
    MyApp,
    ChatsPage,
    MessagesPage,
    LoginPage,
    VerificationPage
  ],
  providers: [
    { provide: ErrorHandler, useClass: IonicErrorHandler },

Now we can make sure that anytime we login, we will be promoted to the VerificationPage right after:

7.19 Import and use verfication page from login client/imports/pages/login/login.ts
1
2
3
4
5
6
7
 
48
49
50
51
52
53
54
55
56
57
58
import { Component } from '@angular/core';
import { Alert, AlertController, NavController } from 'ionic-angular';
import { PhoneService } from '../../services/phone';
import { VerificationPage } from '../verification/verification';
import template from './login.html';
 
@Component({
...some lines skipped...
    alert.dismiss().then(() => {
      return this.phoneService.verify(this.phone);
    })
    .then(() => {
      this.navCtrl.push(VerificationPage, {
        phone: this.phone
      });
    })
    .catch((e) => {
      this.handleError(e);
    });

The last step in our authentication pattern is setting our profile. We will create a Profile interface so the compiler can recognize profile-data structures:

7.20 Add profile interface imports/models.ts
1
2
3
4
5
6
7
8
9
10
export const DEFAULT_PICTURE_URL = '/assets/default-profile-pic.svg';
 
export interface Profile {
  name?: string;
  picture?: string;
}
 
export enum MessageType {
  TEXT = <any>'text'
}

As you can probably notice we also defined a constant for the default profile picture. We will need to make this resource available for use before proceeding. The referenced svg file can be copied directly from the ionicons NodeJS module using the following command:

public/assets$ cp ../../node_modules/ionicons/dist/svg/ios-contact.svg default-profile-pic.svg

Now we can safely proceed to implementing the ProfileComponent:

7.22 Add profile component client/imports/pages/profile/profile.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
import { Component, OnInit } from '@angular/core';
import { AlertController, NavController } from 'ionic-angular';
import { MeteorObservable } from 'meteor-rxjs';
import { Profile } from '../../../../imports/models';
import { ChatsPage } from '../chats/chats';
import template from './profile.html';
 
@Component({
  template
})
export class ProfilePage implements OnInit {
  picture: string;
  profile: Profile;
 
  constructor(
    private alertCtrl: AlertController,
    private navCtrl: NavController
  ) {}
 
  ngOnInit(): void {
    this.profile = Meteor.user().profile || {
      name: ''
    };
  }
 
  updateProfile(): void {
    MeteorObservable.call('updateProfile', this.profile).subscribe({
      next: () => {
        this.navCtrl.push(ChatsPage);
      },
      error: (e: Error) => {
        this.handleError(e);
      }
    });
  }
 
  handleError(e: Error): void {
    console.error(e);
 
    const alert = this.alertCtrl.create({
      title: 'Oops!',
      message: e.message,
      buttons: ['OK']
    });
 
    alert.present();
  }
}
7.23 Add profile template client/imports/pages/profile/profile.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<ion-header>
  <ion-navbar color="whatsapp">
    <ion-title>Profile</ion-title>
 
    <ion-buttons end>
      <button ion-button class="done-button" (click)="updateProfile()">Done</button>
    </ion-buttons>
  </ion-navbar>
</ion-header>
 
<ion-content class="profile-page-content">
  <div class="profile-picture">
    <img *ngIf="picture" [src]="picture">
  </div>
 
  <ion-item class="profile-name">
    <ion-label stacked>Name</ion-label>
    <ion-input [(ngModel)]="profile.name" placeholder="Your name"></ion-input>
  </ion-item>
</ion-content>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
.profile-page-content {
  .profile-picture {
    max-width: 300px;
    display: block;
    margin: auto;
 
    img {
      margin-bottom: -33px;
      width: 100%;
    }
 
    ion-icon {
      float: right;
      font-size: 30px;
      opacity: 0.5;
      border-left: black solid 1px;
      padding-left: 5px;
    }
  }
}
7.24 Add profile style client/main.scss
8
9
10
11
12
@import "imports/pages/chats/chats";
@import "imports/pages/login/login";
@import "imports/pages/messages/messages";
@import "imports/pages/profile/profile";
@import "imports/pages/verification/verification";

Let's redirect users who passed the verification stage to the newly created ProfileComponent like so:

7.25 Use profile component in verification page client/imports/pages/verification/verification.ts
1
2
3
4
5
6
 
29
30
31
32
33
34
35
36
37
38
import { Component, OnInit } from '@angular/core';
import { AlertController, NavController, NavParams } from 'ionic-angular';
import { ProfilePage } from '../profile/profile';
import { PhoneService } from '../../services/phone';
import template from './verification.html';
 
...some lines skipped...
  }
 
  verify(): void {
    this.phoneService.login(this.phone, this.code).then(() => {
      this.navCtrl.setRoot(ProfilePage, {}, {
        animate: true
      });
    });
  }
 

We will also need to import the ProfileComponent in the app's NgModule so it can be recognized:

7.26 Import profile component client/imports/app/app.module.ts
4
5
6
7
8
9
10
 
15
16
17
18
19
20
21
22
 
28
29
30
31
32
33
34
35
import { ChatsPage } from '../pages/chats/chats'
import { LoginPage } from '../pages/login/login';
import { MessagesPage } from '../pages/messages/messages';
import { ProfilePage } from '../pages/profile/profile';
import { VerificationPage } from '../pages/verification/verification';
import { PhoneService } from '../services/phone';
import { MyApp } from './app.component';
...some lines skipped...
    ChatsPage,
    MessagesPage,
    LoginPage,
    VerificationPage,
    ProfilePage
  ],
  imports: [
    IonicModule.forRoot(MyApp),
...some lines skipped...
    ChatsPage,
    MessagesPage,
    LoginPage,
    VerificationPage,
    ProfilePage
  ],
  providers: [
    { provide: ErrorHandler, useClass: IonicErrorHandler },

The core logic behind this component actually lies within the invocation of the updateProfile, a Meteor method implemented in our API which looks like so:

7.27 Added updateProfile method server/methods.ts
1
2
3
4
5
6
 
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { Meteor } from 'meteor/meteor';
import { Chats, Messages } from '../imports/collections';
import { MessageType, Profile } from '../imports/models';
import { check, Match } from 'meteor/check';
 
const nonEmptyString = Match.Where((str) => {
...some lines skipped...
});
 
Meteor.methods({
  updateProfile(profile: Profile): void {
    if (!this.userId) throw new Meteor.Error('unauthorized',
      'User must be logged-in to create a new chat');
 
    check(profile, {
      name: nonEmptyString
    });
 
    Meteor.users.update(this.userId, {
      $set: {profile}
    });
  },
 
  addMessage(type: MessageType, chatId: string, content: string) {
    check(type, Match.OneOf(String, [ MessageType.TEXT ]));
    check(chatId, nonEmptyString);

Adjusting the Messaging System

Now that our authentication flow is complete, we will need to edit the messages, so each user can be identified by each message sent. We will add a restriction in the addMessage method to see if a user is logged in, and we will bind its ID to the created message:

7.28 Added restriction on new message method server/methods.ts
23
24
25
26
27
28
29
30
31
 
40
41
42
43
44
45
46
  },
 
  addMessage(type: MessageType, chatId: string, content: string) {
    if (!this.userId) throw new Meteor.Error('unauthorized',
      'User must be logged-in to create a new chat');
 
    check(type, Match.OneOf(String, [ MessageType.TEXT ]));
    check(chatId, nonEmptyString);
    check(content, nonEmptyString);
...some lines skipped...
    return {
      messageId: Messages.collection.insert({
        chatId: chatId,
        senderId: this.userId,
        content: content,
        createdAt: new Date(),
        type: type

This requires us to update the Message model as well so TypeScript will recognize the changes:

7.29 Added senderId property to Message object imports/models.ts
19
20
21
22
23
24
25
export interface Message {
  _id?: string;
  chatId?: string;
  senderId?: string;
  content?: string;
  createdAt?: Date;
  ownership?: string;

Now we can determine if a message is ours or not in the MessagePage thanks to the senderId field we've just added:

7.30 Use actual ownership of the message client/imports/pages/messages/messages.ts
19
20
21
22
23
24
25
 
28
29
30
31
32
33
34
 
58
59
60
61
62
63
 
68
69
70
71
72
73
74
  message: string = '';
  autoScroller: MutationObserver;
  scrollOffset = 0;
  senderId: string;
 
  constructor(
    navParams: NavParams,
...some lines skipped...
    this.selectedChat = <Chat>navParams.get('chat');
    this.title = this.selectedChat.title;
    this.picture = this.selectedChat.picture;
    this.senderId = Meteor.userId();
  }
 
  private get messagesPageContent(): Element {
...some lines skipped...
  }
 
  findMessagesDayGroups() {
    return Messages.find({
      chatId: this.selectedChat._id
    }, {
...some lines skipped...
 
        // Compose missing data that we would like to show in the view
        messages.forEach((message) => {
          message.ownership = this.senderId == message.senderId ? 'mine' : 'other';
 
          return message;
        });

Chat Options Menu

Now we're going to add the abilities to log-out and edit our profile as well, which are going to be presented to us using a popover. Let's show a popover any time we press on the options icon in the top right corner of the chats view.

A popover, just like a page in our app, consists of a component, view, and style:

7.31 Add chat options component client/imports/pages/chats/chats-options.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
import { Component, Injectable } from '@angular/core';
import { Alert, AlertController, NavController, ViewController } from 'ionic-angular';
import { PhoneService } from '../../services/phone';
import { LoginPage } from '../login/login';
import { ProfilePage } from '../profile/profile';
import template from './chats-options.html';
 
@Component({
  template
})
@Injectable()
export class ChatsOptionsComponent {
  constructor(
    private alertCtrl: AlertController,
    private navCtrl: NavController,
    private phoneService: PhoneService,
    private viewCtrl: ViewController
  ) {}
 
  editProfile(): void {
    this.viewCtrl.dismiss().then(() => {
      this.navCtrl.push(ProfilePage);
    });
  }
 
  logout(): void {
    const alert = this.alertCtrl.create({
      title: 'Logout',
      message: 'Are you sure you would like to proceed?',
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel'
        },
        {
          text: 'Yes',
          handler: () => {
            this.handleLogout(alert);
            return false;
          }
        }
      ]
    });
 
    this.viewCtrl.dismiss().then(() => {
      alert.present();
    });
  }
 
  handleLogout(alert: Alert): void {
    alert.dismiss().then(() => {
      return this.phoneService.logout();
    })
    .then(() => {
      this.navCtrl.setRoot(LoginPage, {}, {
        animate: true
      });
    })
    .catch((e) => {
      this.handleError(e);
    });
  }
 
  handleError(e: Error): void {
    console.error(e);
 
    const alert = this.alertCtrl.create({
      title: 'Oops!',
      message: e.message,
      buttons: ['OK']
    });
 
    alert.present();
  }
}
7.32 Add chat options component client/imports/pages/chats/chats-options.html
1
2
3
4
5
6
7
8
9
10
11
12
13
<ion-content class="chats-options-page-content">
  <ion-list class="options">
    <button ion-item class="option option-profile" (click)="editProfile()">
      <ion-icon name="contact" class="option-icon"></ion-icon>
      <div class="option-name">Profile</div>
    </button>
 
    <button ion-item class="option option-logout" (click)="logout()">
      <ion-icon name="log-out" class="option-icon"></ion-icon>
      <div class="option-name">Logout</div>
    </button>
  </ion-list>
</ion-content>
7.33 Added chat options stylesheets client/imports/pages/chats/chats-options.scss
1
2
3
4
5
6
7
8
9
10
11
12
13
.chats-options-page-content {
  .options {
    margin: 0;
  }
 
  .option-name {
    float: left;
  }
 
  .option-icon {
    float: right;
  }
}
7.33 Added chat options stylesheets client/main.scss
6
7
8
9
10
11
12
 
// Pages
@import "imports/pages/chats/chats";
@import "imports/pages/chats/chats-options";
@import "imports/pages/login/login";
@import "imports/pages/messages/messages";
@import "imports/pages/profile/profile";

It requires us to import it in the NgModule as well:

7.34 Import chat options client/imports/app/app.module.ts
2
3
4
5
6
7
8
 
17
18
19
20
21
22
23
24
 
31
32
33
34
35
36
37
38
import { MomentModule } from 'angular2-moment';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { ChatsPage } from '../pages/chats/chats'
import { ChatsOptionsComponent } from '../pages/chats/chats-options';
import { LoginPage } from '../pages/login/login';
import { MessagesPage } from '../pages/messages/messages';
import { ProfilePage } from '../pages/profile/profile';
...some lines skipped...
    MessagesPage,
    LoginPage,
    VerificationPage,
    ProfilePage,
    ChatsOptionsComponent
  ],
  imports: [
    IonicModule.forRoot(MyApp),
...some lines skipped...
    MessagesPage,
    LoginPage,
    VerificationPage,
    ProfilePage,
    ChatsOptionsComponent
  ],
  providers: [
    { provide: ErrorHandler, useClass: IonicErrorHandler },

Now we will implement the method in the ChatsPage which will initialize the ChatsOptionsComponent using a popover controller:

7.35 Added showOptions method client/imports/pages/chats/chats.ts
1
2
3
4
5
6
7
8
9
10
 
14
15
16
17
18
19
20
21
22
 
45
46
47
48
49
50
51
52
53
54
55
56
import { Component, OnInit } from '@angular/core';
import { NavController, PopoverController } from 'ionic-angular';
import * as Moment from 'moment';
import { Observable } from 'rxjs';
import { Chats, Messages } from '../../../../imports/collections';
import { Chat, 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;
 
  constructor(
    private navCtrl: NavController,
    private popoverCtrl: PopoverController) {
  }
 
  ngOnInit() {
...some lines skipped...
    Chats.remove({_id: chat._id}).subscribe(() => {
    });
  }
 
  showOptions(): void {
    const popover = this.popoverCtrl.create(ChatsOptionsComponent, {}, {
      cssClass: 'options-popover chats-options-popover'
    });
 
    popover.present();
  }
}

The method is invoked thanks to the following binding in the chats view:

7.36 Bind click event to showOptions method client/imports/pages/chats/chats.html
7
8
9
10
11
12
13
      <button ion-button icon-only class="add-chat-button">
        <ion-icon name="person-add"></ion-icon>
      </button>
      <button ion-button icon-only class="options-button" (click)="showOptions()">
        <ion-icon name="more"></ion-icon>
      </button>
    </ion-buttons>

As for now, once you click on the options icon in the chats view, the popover should appear in the middle of the screen. To fix it, we gonna add the extend our app's main stylesheet, since it can be potentially used as a component not just in the ChatsPage, but also in other pages as well:

7.37 Added chat options popover stylesheet client/imports/app/app.scss
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Put style rules here that you want to apply globally. These
// styles are for the entire app and not just one component.
// Additionally, this file can be also used as an entry point
// to import other Sass files to be included in the output CSS.
 
 
// Options Popover Component
// --------------------------------------------------
 
$options-popover-width: 200px;
$options-popover-margin: 5px;
 
.options-popover .popover-content {
  width: $options-popover-width;
  transform-origin: right top 0px !important;
  left: calc(100% - #{$options-popover-width} - #{$options-popover-margin}) !important;
  top: $options-popover-margin !important;
}

{{{nav_step prev_ref="https://angular-meteor.com/tutorials/whatsapp2/meteor/messages-page" next_ref="https://angular-meteor.com/tutorials/whatsapp2/meteor/chats-mutations"}}}