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 server and add few Meteor
packages called accounts-base
and accounts-phone
which will give us the ability to verify a user using an SMS code, so run the following inside api
directory:
api$ meteor add accounts-base
api$ meteor add npm-bcrypt
api$ meteor add mys:accounts-phone
Be sure to keep your Meteor
client script updated as well by running:
$ npm run meteor-client:bundle
For the sake of debugging we gonna write an authentication settings file (api/private/settings.json
) which might make our life easier, but once you're in production mode you shouldn't use this configuration:
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
:
api$ meteor run --settings private/settings.json
To make it simpler we can add a script called api
script to the package.json
which will start the Meteor server:
9
10
11
12
13
14
15
"url": "https://github.com/Urigo/Ionic2CLI-Meteor-WhatsApp.git"
},
"scripts": {
"api": "cd api && meteor run --settings private/settings.json",
"clean": "ionic-app-scripts clean",
"build": "ionic-app-scripts build",
"lint": "ionic-app-scripts lint",
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:
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { Messages } from './collections/messages';
import * as moment from 'moment';
import { MessageType } from './models';
import { Accounts } from 'meteor/accounts-base';
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:
$ npm install --save-dev @types/meteor-accounts-phone
And we will reference from the tsconfig
like so:
16
17
18
19
20
21
22
23
"stripInternal": true,
"noImplicitAny": false,
"types": [
"@types/meteor",
"@types/meteor-accounts-phone"
]
},
"exclude": [
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import 'meteor-client';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { MeteorObservable } from 'meteor-rxjs';
import { Meteor } from 'meteor/meteor';
import { AppModule } from './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
:
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
import { Injectable } from '@angular/core';
import { Accounts } from 'meteor/accounts-base';
import { Meteor } from 'meteor/meteor';
@Injectable()
export class PhoneService {
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:
6
7
8
9
10
11
12
29
30
31
32
33
34
35
36
import { MomentModule } from 'angular2-moment';
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...
providers: [
StatusBar,
SplashScreen,
{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:
zone
, which means the view will be updated automatically once the callback has been invoked.Observable
.Just so the TypeScript
compiler will know how to digest it, we shall also specify the accounts-phone
types in the client tsconfig.json
as well:
20
21
22
23
24
25
26
27
"stripInternal": true,
"noImplicitAny": false,
"types": [
"@types/meteor",
"@types/meteor-accounts-phone"
]
},
"include": [
For authentication purposes, we gonna create the following flow in our app:
Let's start by creating the LoginComponent
. In this component we will request an SMS verification right after a phone number has been entered:
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';
@Component({
selector: 'login',
templateUrl: 'login.html'
})
export class LoginPage {
private 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:
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:
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;
}
}
And as usual, newly created components should be imported in the app's module:
5
6
7
8
9
10
11
14
15
16
17
18
19
20
21
26
27
28
29
30
31
32
33
import { StatusBar } from '@ionic-native/status-bar';
import { MomentModule } from 'angular2-moment';
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: [
BrowserModule,
...some lines skipped...
entryComponents: [
MyApp,
ChatsPage,
MessagesPage,
LoginPage
],
providers: [
StatusBar,
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:
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { ChatsPage } from '../pages/chats/chats';
import { Meteor } from 'meteor/meteor';
import { LoginPage } from '../pages/login/login';
@Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage: any;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
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
:
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';
@Component({
selector: 'verification',
templateUrl: 'verification.html'
})
export class VerificationPage implements OnInit {
private code: string = '';
private 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();
}
}
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>
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;
}
}
And add it to the NgModule
:
7
8
9
10
11
12
13
16
17
18
19
20
21
22
23
29
30
31
32
33
34
35
36
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: [
BrowserModule,
...some lines skipped...
MyApp,
ChatsPage,
MessagesPage,
LoginPage,
VerificationPage
],
providers: [
StatusBar,
Now we can make sure that anytime we login, we will be promoted to the VerificationPage
right after:
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';
@Component({
selector: 'login',
...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:
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:
src/assets$ cp ../../node_modules/ionicons/dist/svg/ios-contact.svg default-profile-pic.svg
Now we can safely proceed to implementing the ProfileComponent
:
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 { Profile } from 'api/models';
import { AlertController, NavController } from 'ionic-angular';
import { MeteorObservable } from 'meteor-rxjs';
import { ChatsPage } from '../chats/chats';
@Component({
selector: 'profile',
templateUrl: 'profile.html'
})
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();
}
}
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;
}
}
}
Let's redirect users who passed the verification stage to the newly created ProfileComponent
like so:
1
2
3
4
5
6
7
29
30
31
32
33
34
35
36
37
38
39
import { Component, OnInit } from '@angular/core';
import { AlertController, NavController, NavParams } from 'ionic-angular';
import { PhoneService } from '../../services/phone';
import { ProfilePage } from '../profile/profile';
@Component({
selector: 'verification',
...some lines skipped...
}
verify(): void {
this.phoneService.login(this.phone, this.code).then(() => {
this.navCtrl.setRoot(ProfilePage, {}, {
animate: true
});
})
.catch((e) => {
this.handleError(e);
});
We will also need to import the ProfileComponent
in the app's NgModule
so it can be recognized:
7
8
9
10
11
12
13
18
19
20
21
22
23
24
25
32
33
34
35
36
37
38
39
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: [
BrowserModule,
...some lines skipped...
ChatsPage,
MessagesPage,
LoginPage,
VerificationPage,
ProfilePage
],
providers: [
StatusBar,
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:
1
2
3
4
5
6
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { Chats } from './collections/chats';
import { Messages } from './collections/messages';
import { MessageType, Profile } from './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);
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:
22
23
24
25
26
27
28
29
30
39
40
41
42
43
44
45
});
},
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:
19
20
21
22
23
24
25
export interface Message {
_id?: string;
chatId?: string;
senderId?: string;
content?: string;
createdAt?: Date;
type?: MessageType
Now we can determine if a message is ours or not in the MessagePage
thanks to the senderId
field we've just added:
18
19
20
21
22
23
24
27
28
29
30
31
32
33
57
58
59
60
61
62
67
68
69
70
71
72
73
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;
});
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:
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';
@Component({
selector: 'chats-options',
templateUrl: 'chats-options.html'
})
@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();
}
}
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>
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;
}
}
It requires us to import it in the NgModule
as well:
5
6
7
8
9
10
11
20
21
22
23
24
25
26
27
35
36
37
38
39
40
41
42
import { StatusBar } from '@ionic-native/status-bar';
import { MomentModule } from 'angular2-moment';
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: [
BrowserModule,
...some lines skipped...
MessagesPage,
LoginPage,
VerificationPage,
ProfilePage,
ChatsOptionsComponent
],
providers: [
StatusBar,
Now we will implement the method in the ChatsPage
which will initialize the ChatsOptionsComponent
using a popover controller:
1
2
3
4
5
6
7
8
9
10
12
13
14
15
16
17
18
19
20
43
44
45
46
47
48
49
50
51
52
53
54
import { Component, OnInit } from '@angular/core';
import { Chats, Messages } from 'api/collections';
import { Chat } from 'api/models';
import { NavController, PopoverController } from 'ionic-angular';
import { Observable } from 'rxjs';
import { MessagesPage } from '../messages/messages';
import { ChatsOptionsComponent } from './chats-options';
@Component({
templateUrl: '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
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:
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// To declare rules for a specific mode, create a child rule
// for the .md, .ios, or .wp mode classes. The mode class is
// automatically applied to the <body> element in the app.
// 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;
}