Build a live poll app with Ionic

  • Christian Nwamba
June 26th, 2018
You will need Node and npm installed on your machine. A basic knowledge of Angular, Ionic and Node will be helpful.

Introduction

An electronic polling system allows users cast their votes with ease without the hassle and stress of visiting a polling booth. This makes it easily accessible as it can be used by users anywhere in the world. Adding realtime functionality to the application improves the user experience as votes are seen in realtime.

We’ll build a realtime polling application using Pusher, Node, and Ionic. Using our application, users will get to vote for their favorite soccer player in the English Premier League. Here’s a demo of the final product:

We’ll send our votes to the server and with the help of Pusher, update our polls in realtime. To make use of Pusher, you’ll have to create an account here.

Let’s build!

Prerequisites

To follow this tutorial a basic understanding of Angular, Ionic and Node.js is required. Please ensure that you have Node and npm installed before you begin. If you have no prior knowledge of Ionic, kindly follow the tutorial here. Come back and finish the tutorial when you’re done.

We’ll be using these tools to build out our application:

  1. Express
  2. Node
  3. Pusher
  4. Ionic

Setup and folder structure

To get started, we will use the CLI (command line interface) provided by the Ionic team to initialize our project.

First, install the CLI by running npm install -g ionic cordova. NPM is a package manager used for installing packages. It will be available on your PC if you have Node installed.

To create a new Ionic App using the CLI, open a terminal and run:

    ionic start pollApp blank

The command is merely telling the CLI to create a new app called pollApp and it should make use of the blank starter template. While the setup is running you might get a prompt "Would you like to integrate your new app with Cordova to target native iOS and Android?". If you want to start running or testing the application on a mobile device or emulator as you build, then choose yes by typing Y and pressing Enter on your keyboard, else type N and continue. You might get another prompt "If you would like to integrate ionic pro ?" , we wouldn’t be needing that in this tutorial so just type N and if you would like extend the project into production with your team choose Y.

Open the newly created pollApp. Your folder structure should look something like this:

    pollApp /
      node_modules /
      src / 
        app /
          assets /
          pages /
            home /
              home.html
              home.ts
              home.scss

Open a terminal inside the app folder and start the application by running:

    ionic serve 

Automatically your default browser should open, and you should see the screenshot below if everything went well.

Building our server

Now that we have our Ionic application running let’s build our server. To do this, we’ll need to install Express. Express is a fast, unopinionated, minimalist web framework for Node.js. We’ll use this to receive requests from our Ionic application.

Run npm install express on a terminal inside the root folder of your project to install Express. Create a file called server.js in the root of the project and update it with the code snippet below:

    //pollApp/server.js

    require('dotenv').config();
    const express = require('express');
    const bodyParser = require('body-parser');
    const Pusher = require('pusher');

    const app = express();
    const port = process.env.PORT || 4000;
    const pusher = new Pusher({
      appId: process.env.PUSHER_APP_ID,
      key: process.env.PUSHER_KEY,
      secret: process.env.PUSHER_SECRET,
      cluster: process.env.CLUSTER,
      encrypted: true,
    });

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use((req, res, next) => {
      res.header('Access-Control-Allow-Origin', '*');
      res.header(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Content-Type, Accept'
      );
      next();
    });

    app.listen(port, () => {
      console.log(`Server started on port ${port}`);
    });

We referenced three packages that we are yet to install, body-parser, pusher and dotenv. Install these packages by running this code in your terminal:

    npm i body-parser pusher dotenv

The body-parser package is used to parse incoming request bodies in a middleware before your handlers, available under the req.body property.

The calls to our endpoint will be coming in from a different origin. Therefore we need to make sure we include the CORS headers (Access-Control-Allow-Origin). If you are unfamiliar with the concept of CORS headers, you can find more information here.

This is a standard Node application configuration, nothing specific to our app. Also, you’ll notice that we installed Pusher library as a dependency. Create a Pusher account and a new Pusher Channels app and get your appId, key and secret.

The last package, dotenv is a zero-dependency module that loads environment variables from a .env file into process.env.

We use this package to make sure we don’t add sensitive information like our appId and secret directly into our code. To get these values loaded into our environment, we'll create a .env file in the root of our project.

Your .env file should look something like the snippet below. We’ll add our Pusher appId, key and secret provided here.

    // pollApp/.env
    PUSHER_APP_ID=<APP_ID>
    PUSHER_KEY=<PUSHER_KEY>
    PUSHER_SECRET=<PUSHER_SECRET>
    CLUSTER=<CLUSTER>

If you noticed, we added the dotenv package at the start of our file. This is done because we need to make the variables available throughout the file. Please ensure you replace the following placeholder values above with your unique Pusher appId, key and secret from your Pusher dashboard.

Send votes

To enable users send requests to the server, we’ll create a route to handle incoming requests. Update your server.js file with the code below:

    // pollApp/server.js
    require('dotenv').config();
    ...
    app.post('/vote', (req, res) => {
      const { body } = req;
      const { player } = body;
      pusher.trigger('vote-channel', 'vote', {
        player,
      });
      res.json({ player });
    });

     ...

We created a POST /vote route which, when hit, triggers a Pusher event. We used object destructuring to get the body of the request and also the player info sent by the user.

The trigger is achieved using the trigger``() method which takes the trigger identifier (vote-channel), an event name (vote), and a payload. The payload can be any value, but in this case, we have a JS object. This object contains the name of the player being voted for.

We still go ahead to respond with an object containing the voted player string so we can update the frontend with the data.

Building the app UI

Open home.html and replace it with the content below:

    //../src/pages/home/home.html

    <ion-header>
      <ion-navbar>
        <ion-title>
        Poll APP  
        </ion-title>
      </ion-navbar>
    </ion-header>
    <ion-content padding>
      <ion-list no-lines>
        <ion-item *ngFor="let player of playerData">
          <ion-row>
            <ion-col col-6>
                <ion-avatar>
                    <img [src]="player.image" [alt]="player.name" [ngClass]="getVoteClasses(player.shortName)">
                    <h4>{{player.name}}</h4>
                    <p>{{player.goals}} goals</p>
                    <p>{{player.assists}} assists</p>
                  </ion-avatar>
            </ion-col>
            <ion-col col-6>
                  <h1>VoteCount</h1>
                  <h1 text-center>{{voteCount[player.shortName]}}</h1>
            </ion-col>
          </ion-row> 
          <button ion-button full round (click)="sendVotes(player)">Vote</button>
        </ion-item>
      </ion-list>
    </ion-content>

In the code snippet above, we looped through playerData``[] to create a view based on the player’s information. There are some undefined variables in the code snippet above, don’t panic yet, we’ll define them in our home.ts file below.

Home.ts

In the HTML snippet, we referred to some variables that weren’t yet defined. We’ll create the variables here with the logic behind our application, and import the HttpClient service.

    // ../src/pages/home/home.ts
    import { HttpClient } from '@angular/common/http';
    import { Component } from '@angular/core';
    import { NavController } from 'ionic-angular';

    @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
    })
    export class HomePage {
      constructor(public navCtrl: NavController, public http : HttpClient) {
      }
      event: string = 'vote';
      vote: string = '';
      ifVoted : boolean = false;
      voteCount = {
        salah: 0,
        kane: 0,
        eriksen: 0,
        kevin: 0,
      };
      playerData = [
        {
          name: 'Mo. Salah',
          goals: 30,
          assists: 12,
          shortName: 'salah',
          image: 'https://platform-static-files.s3.amazonaws.com/premierleague/photos/players/250x250/p118748.png'
        },
        {
          name: 'Christian Eriksen',
          goals: 8,
          assists: 13,
          shortName: 'eriksen',
          image: 'https://platform-static-files.s3.amazonaws.com/premierleague/photos/players/250x250/p80607.png',
        },
        {
          name: 'Harry Kane',
          goals: 26,
          assists: 5,
          shortName: 'kane',
          image:
            'https://platform-static-files.s3.amazonaws.com/premierleague/photos/players/40x40/p78830.png',
        },
        {
          name: "Kevin De'bruyne",
          goals: 10,
          assists: 17,
          shortName: 'kevin',
          image: 'https://platform-static-files.s3.amazonaws.com/premierleague/photos/players/40x40/p61366.png',
        },
    ];
      sendVotes(player){
        this.http.post('http://localhost:4000/vote', { player }).subscribe((res : any) => {
          this.vote  = res.player;
          this.ifVoted = true;
        })
      }
      getVoteClasses(player){
        return {
          elect : this.ifVoted && this.vote === player,
          lost : this.ifVoted && this.vote !== player
        }
      }
      ionViewDidLoad(){}
    }

send``Votes``(): this method makes use of the native HttpClient service to make requests to our server. It sends the name of the player being voted for in a POST request to the server. When a response is returned, it sets the voted property to true signifying that the user has placed a vote. Also, it sets the vote property to the name of the player being voted.

getVoteClasses``(): this method sets classNames on each player element based on if a player was voted for or not.

To make use of the HttpClient service, we’ll need to import the HttpClientModule into the app.module.ts file. Update your app module file as follows:

    // src/app/app.module.ts

    import { BrowserModule } from '@angular/platform-browser';
    import { ErrorHandler, NgModule } from '@angular/core';
    import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
    import { SplashScreen } from '@ionic-native/splash-screen';
    import { StatusBar } from '@ionic-native/status-bar';
    import { HttpClientModule } from '@angular/common/http';
    import { MyApp } from './app.component';
    import { HomePage } from '../pages/home/home';
    @NgModule({
    declarations: [
    MyApp,
    HomePage
    ],
    imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpClientModule
    ],
    bootstrap: [IonicApp],
    ....

By now our application should look like this:

Introducing Pusher

So far we have an application that enables users to cast votes, but we have no way of keeping track of how others voted in realtime. We also have no way of visualizing the polling data. To solve both of these problems, we’ll include the Pusher library.

Open index.html file in the src folder of the project and paste the cdn into it:

    ...

      <script src="https://js.pusher.com/4.1/pusher.min.js"></script>
      <!-- add to homescreen for ios --> 
    ...

Now that Pusher has been made available in our project, we’ll create a Pusher Provider to be used in our application. The Ionic CLI can aid in the provider creation. Open a terminal in your project’s root folder and run the following command:

    ionic generate provider pusher-service

This command simply tells the CLI to generate a provider named pusher. Now open the pusher-service.ts file and update it with the code below:

    // ../src/providers/pusher-service/pusher-service.ts

    import { HttpClient } from '@angular/common/http';
    import { Injectable } from '@angular/core';
    declare const Pusher: any;
    @Injectable()
    export class PusherServiceProvider {
    channel;
    constructor(public http: HttpClient) {
    var pusher = new Pusher('<PUSHER_KEY>', {
    cluster: 'eu',
    encrypted: true,
    });
    this.channel = pusher.subscribe('vote-channel');
    }
    public init(){
      return this.channel;
      }
    }

First, we initialize Pusher in the constructor. The init() method returns the Pusher property we created. Ensure you replace the PUSHER_KEY string with your actual Pusher key.

To make the provider available in the application, import it into the app.``module.ts file.

    // ../src/app/app.module.ts

    import { PusherServiceProvider } from '../providers/pusher-service/pusher-service';
    ....
    providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    PusherServiceProvider
    ]
    ....

We’ll make use of this provider in our home page, by binding to the vote event and increment the votes of the voted player returned in the event. This will be done in the ionViewDidLoad lifecycle.

    // ../src/pages/home/home.ts

    import { PusherServiceProvider } from '../../providers/pusher-service/pusher-service';

    constructor(public navCtrl: NavController, public http : HttpClient, private pusher : PusherServiceProvider) {}

    ...

    ionViewDidLoad(){
      const channel = this.pusher.init();
      channel.bind(this.event, ({ player }) => {
        this.voteCount[player.shortName] += 1
      });
    }

At this point, your application should have realtime updates when votes are placed. Ensure that the server is running alongside the Ionic development server. If not, run node server and ionic serve in two separate terminals. Both terminals should be opened in the root folder of your project.

Testing on Mobile Devices

To test the application on your mobile device, download the IonicDevApp on your mobile device. Make sure your computer and your mobile device are connected to the same network. When you open the IonicDevApp, you should see Ionic apps running on your network listed.

Note: Both the server(node server), ngrok for proxying our server and the Ionic dev server(ionic serve) must be running to get the application working. Run the commands in separate terminal sessions if you haven’t done so already.

To view the application, click on it and you should see a similar view to what was in the browser. Sending messages to the server might have worked in the browser but localhost doesn’t exist on your phone, so we’ll need to create a proxy to be able to send messages from mobile.

You can also run the following code in your terminal if the above method doesn’t work for you.

    ionic cordova run <target_platform>
  • target_platform : either ios or android

Using Ngrok as a proxy

To create a proxy for our server, we’ll download Ngrok. Visit the download page on the Ngrok website. Download the client for your OS. Unzip it and run the following command in the folder where Ngrok can be found:

    ./ngrok http 4000

Copy the forwarding url with https and place it in the home.ts file that previously had http://localhost:4000/``vote. Please do not copy mine from the screenshot above.

    // src/pages/home/home.ts
    ...
    @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
    })
    export class HomePage {
      ...
       sendVotes(player){
          this.http.post('<NGROK_URL>/vote', { player }).subscribe((res : any) => {
          this.vote  = res.player;
          this.ifVoted = true;
        });
      }
      ...
    }
    ...

Ensure to include the forwarding URL you copied where the placeholder string is

Now you should be seeing realtime update of the votes, both on the phone and the browser.

Note: Both the server(node server), ngrok for proxying our server and the Ionic dev server(ionic serve) must be running to get the application working. Run the commands in separate terminal sessions if you haven’t done so already.

To build your application to deploy on either the AppStore or PlayStore, follow the instructions found here.

Conclusion

Using Pusher, we’ve built out an application using the pub/sub pattern without having to set up a WebSocket server. This shows how powerful Pusher is and how easy it is to set up. You can find the demo for this article on GitHub.

  • Channels

© 2018 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.