Ionic Chat Basic Tutorial

Adam Bavosa
9 min readJan 11, 2019

--

This tutorial is for the beginner Ionic TypeScript software developer. You can also get started with the Ionic Chat GitHub repository.

Ionic is a framework that empowers you to build native Android apps in Angular. It’s a great choice, not just for its support of Cordova, but also because it provides some nice UI components, and is built on top of Angular’s robust framework. It’ll let you build mobile apps with a consistent look and feel, and a modular and componentized architecture which makes development and maintenance easy.

In this tutorial, we’ll walk through how to build a basic Android chat app with Ionic and PubNub ChatEngine. We’ll create our beautiful mobile frontend with Ionic, and ChatEngine will power all the chat features and backend infrastructure.

We will start the code section of this walkthrough. And you will need the: Ionic Chat GitHub Repository.

Before you proceed, here are the things that you must know to understand the steps involved in building this app. Ionic is based on Angular, so some familiarity with Angular and Typescript language is preferred. You can also check out this tutorial on building a web based chat app using Angular and ChatEngine.

Step 1 : Environment Setup

Let’s up set up the environment first. We need the Ionic CLI tools to create a new project workspace and then install the necessary node packages as follows.

Note: While installing Ionic, make sure to choose N (No) when prompted for installation of Ionic v4. Ionic v4 is still in beta and we will be using Ionic v3 for this app.

This will setup the app environment for you and the browser will launch with blank UI template. You can also emulate the native app UI for Android and iOS by running Ionic Lab. ionic lab This will open a browser tab and emulate the app UI as per the native platform. It supports iOS, Android as well as Windows. Here is how the ionic lab interface looks like for the Android version of chat app.

The ionic lab command is an alternative to ionic serve --lab. Do not confuse it with the ionic lab desktop app which has already been sunsetted by the Ionic team.

Now we will add some code to convert this blank UI template into a functional chat app as shown above. Keep the ionic lab command running on the terminal. As we add more code to the application, the browser will refresh to render the app UI.

Step 2 : ChatEngine Setup

In order to use the ChatEngine we have to install it via the npm tool within the newly created app environment.

npm install chat-engine --save

With this, we are all set in terms of the tooling and the library dependencies required for building this app. Let’s go ahead and write some code.

Step 3 : Create the ChatEngine Service

Before we can use the services of the ChatEngine framework, we need to bind it to the Ionic app. Since Ionic is based on Angular, we follow the Angular way, by creating a service that wraps the ChatEngine into an Angular Service named chatengine.

IonicChatengineBasicApp/src/app/chatengine.ts (New File)

Since, ChatEngine relies on the PubNub’s Data Stream Network, we need the PubNub Publish and Subscribe keys to make this work. To get your FREE keys follow this form.

  1. The generated keys will be displayed on your screen.
  2. Replace the newly generated Publish key and Subscribe key with the string <YOUR-PUBNUB-PUBLISH-KEY> and <YOUR-PUBNUB-SUBSCRIBE-KEY> in the chatengine.ts

Step 4: Binding the ChatEngine Service with Ionic App

Now that we have the ChatEngine service available, we need to inject it into the app.module to make it available for the app. Again, we follow the Angular way and modify the app.module.ts file to inject the ChatEngine service.

IonicChatengineBasicApp/src/app/app.module.ts (Modified File)

Step 5: Building the App UI

With step 4 we have achieved all the base code for the app. Now it is time to build the UI functionality on top of that. Ionic comes with inbuilt UI components to render visual elements in multiple pages. For this app we are going to use only a single page, that is the chat UI page. We will follow the Ionic’s recommended structure and split the chat UI page into the header, content and footer sections.

For displaying the chat messages, we use the <ion-list> with <ion-grid> UI elements.

The entire HTML code of the app UI is declared in home.html. You can overwrite the file as per the new UI declaration for this app.

IonicChatengineBasicApp/src/page/home/home.html (Modified File)

All chat messages are added inside the <ion-content> tag as stacked <ion-item> tags within an <ion-list>. The <ion-items> are added iteratively using the Angular’s ngFor directive.

Within each <ion-item>, we have used the ngIf Angular directive to distinguish the chat users. The chat messages send from an app client appear on the right, while the messages arriving from other users appear as left aligned.

We have added a few styles to add some finesse to the timestamp and the footer elements. The styles are defined in home.scss file which is a blank file by default.

IonicChatengineBasicApp/src/page/home/home.scss (Modified File)

Step 6: Coding the Business Logic for App UI

With the UI, we are almost close to having a fully functional app. The last missing piece is the the UI component code for the chat UI page. This is defined as home.ts which serves as the backend Component code of the chat UI page. You can overwrite this file as follows.

IonicChatengineBasicApp/src/page/home/home.ts (Modified File)

That is quite a bit of typescript code. Let’s dissect the code by analyzing the member methods of the class HomePage which represents the component backend of chat UI page (home.html).

A. Constructor

The constructor initializes the MutationObserver which is required for auto scrolling of chat messages in the screen. Apart from this, the class also has some member variables which get initialized. The most notable of them are isInitialized - Contains a boolean flag to indicate the initialization state of the ChatEngine.

messages - An array of all the chat messages since the app was launched and user entered the chat room. message - A string that holds the current message being typed by the chat user. It has a two way data binding with the <input> tag, set via (ngModel) Angular directive.

B. chatInitialize()

This method initializes the ChatEngine and sets up the event handlers for handling an incoming message. Every incoming message is time stamped in HH:MM format which is contained in the rcvdTime object property. Another property isSelf is added to check whether the message originated from the same app client. isSelf and rcvdTime are referenced within the HTML code to decide the chat message alignment and display the timestamp of each chat message within ion-item.

C. getUsers( )

This method is used to retrieve all the users who have joined the chat room. This is used to populate the header section of the UI to display all the users that are currently present in the chat room.

D. send( )

This method is used to send the chat message from the app client. It is bound to the <input> box as well as the <button> element of the UI.

E. chatLeave()

This is the opposite of chatInitialize( ). This method will force the user to leave the chat room and disconnect the ChatEngine.

F. getCurrentTime( ) & generatePerson( )

These two methods are used internally. getCurrentTIme( ) generates a local timestamp of the chat message. generatePerson( ) is a method that generates a random user profile which mainly includes a name and an avatar.

G. ionViewDidLoad( ) & ionViewWillUnload( )

These two are the Ionic’s lifecycle events which are fired when the page is loaded and unloaded. ionViewDidLoad( ) is called when the page loads. ionViewWillUnload( ) is called just before the page is taken out of the view in response to the back button.

Next Steps

We now have a basic functional chat app built with Ionic Framework. You can check out the GitHub repo for the complete code of this app. Now you can compile it into an Android or an iOS app and test it out on a native device.

Deployment for Android

Follow these steps for installing the dependencies and deploying this app for Android.

Step 1 — Install the tools and dependent packages

  1. Install Android Studio
  2. Install the cordova SDK ( npm install -g cordova)
  3. Inside android studio sdk manager, install the sdks from latest API level upto API level 16
  4. Install Gradle
  5. Install JAVA8 from the Oracle download site
  6. Set JAVA_HOME environment variable to java-8-oracle
  7. Set ANDROID_HOME environment variable to android studio’s sdk directory
  8. Install Genymotion emulator personal use edition

Step 2 — Converting Ionic app to Android

  1. Navigate to the ionic project directory (Command: cd IonicChatengineBasicApp )
  2. Add the platform ( Command: ionic cordova platform add android )
  3. Check whether all the requirements are installed or not (Command: ionic cordova requirements )
  4. Build the app ( Command: ionic cordova build android )
  5. Run the app on emulator ( Command: ionic cordova run android ) ,Make sure your emulator is up and running before executing this command.

Deployment for iOS

Follow these steps for installing the dependencies and deploying this app for iOS.

Step 1 — Prerequisites

  1. Install xcode sdk
  2. Set all the necessary environment variables
  3. Install an emulator

Step 2 — Converting ionic app to iOS

  1. Navigate to Ionic project directory
  2. Add the platform ( Command: ionic cordova platform add ios )
  3. Build the app ( Command: ionic cordova build ios )
  4. Run the app on the emulator ( Command: ionic cordova run ios )

There are many, many different flavors of mobile chat. Private chat in a dating app, doctor:patient chat in a HIPAA-compliant app, in-game chat in a multiplayer game, chat with your delivery driver, or even getting customer support with an automated chatbot. Chat is the new norm for communication, and use cases and user adoption will only keep growing. To put it simply, everyone uses mobile chat.

Security

If it’s connected to the Internet, assume someone is going to try to hack it. That’s why security in chat is mission critical. But it’s hard to get right, so picking the right frameworks, protocols, and infrastructure will save you headaches in the short term and the long run.

Good news for you, ChatEngine with Ionic was built for security first. With AES/TLS encryption baked in, and access management features at your fingertips, you can ensure a secure and safe mobile chat experience your users will love.

Reliability and Scale

When it comes to building chat applications, ensuring reliability and scale in the lab is easy, but out in the wild, it’s a whole other ball game. You need a backend that stays reliable no matter how many users are concurrently connected, no matter where on Earth users are located, and no matter how unreliable users’ network connections are.

PubNub is globally scaled with 15 points of presence across the globe, so you get low-latency chat anywhere on Earth. And with a ton of features focusing on reliability like message catchup/caching and fast, efficient realtime protocols, your chat app scales as your users grow, without all the headaches of maintaining and orchestrating a messaging backend.

Originally published at ionic.chat.

--

--