Build a realtime poll using Angular

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.

Using Angular you can extend the template language with your own components and use a wide array of existing components.

To follow this tutorial a basic understanding of Angular and Node.js is required. Please ensure that you have Node and npm installed before you begin.

If you have no prior knowledge of Angular, 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:

We’ll build a realtime polling application using Pusher , Angular and charts.js for data visualization.

Using our application users will get to vote for their favourite soccer player in the English Premier League.

Here’s a demo of the final product:

angular-football-poll-demo

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!

Setup and folder structure

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

First, install the CLI by running npm install -g @angular/cli. 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 Angular project using the CLI, open a terminal and run
ng new angular-realtime-polling --``style=scss

The command is simply telling the CLI to create a new project called angular-realtime-polling and it should make use of the CSS pre-processor SCSS rather than CSS for styling.

Open the newly created angular-realtime-polling. Your folder structure should look something like this:

1angular-realtime-polling/
2      e2e/
3      node_modules/
4      src/
5        app/
6          app.component.html
7          app.component.ts
8          app.component.css
9          ...

Open a terminal inside the project folder and start the application by running ng serve . If you open your browser and visit the link http://localhost:4200 you should see the screenshot below if everything went well.

tables-angular-welcome-screen

Building our server

Now that we have our Angular 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 Angular 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

1require('dotenv').config();
2    const express = require('express');
3    const bodyParser = require('body-parser');
4    const Pusher = require('pusher');
5    
6    const app = express();
7    const port = process.env.PORT || 4000;
8    const pusher = new Pusher({
9      appId: process.env.PUSHER_APP_ID,
10      key: process.env.PUSHER_KEY,
11      secret: process.env.PUSHER_SECRET,
12      cluster: 'eu',
13      encrypted: true,
14    });
15    
16    app.use(bodyParser.json());
17    app.use(bodyParser.urlencoded({ extended: false }));
18    app.use((req, res, next) => {
19      res.header('Access-Control-Allow-Origin', '*');
20      res.header(
21        'Access-Control-Allow-Headers',
22        'Origin, X-Requested-With, Content-Type, Accept'
23      );
24      next();
25    });
26    
27    app.listen(port, () => {
28      console.log(`Server started on port ${port}`);
29    });

We referenced three packages that haven’t been installed, body-parser, pusher and dotenv. Install these packages by running npm i body-parser pusher dotenv in your terminal.

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 if you haven’t done so yet 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 so 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.

1PUSHER_APP_ID=<APP_ID>
2    PUSHER_KEY=<PUSHER_KEY>
3    PUSHER_SECRET=<PUSHER_SECRET>

If you noticed, I 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 Pusher appId, key and secret.

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.

1// server.js
2    require('dotenv').config();
3    ...
4    
5    app.post('/vote', (req, res) => {
6      const { body } = req;
7      const { player } = body;
8      pusher.trigger('vote-channel', 'vote', {
9        player,
10      });
11      res.json({ player });
12    });
13    
14     ...
  • 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

Polling view

Open the app.component.html file and replace it with the content below.

1// app.component.html
2    
3    <div>
4      <h2>Vote for your player of the season</h2>
5      <ul>
6        <li *ngFor="let player of playerData">
7          <img [src]="player.image" [alt]="player.name" (click)="castVote(player.shortName)" [ngClass]="getVoteClasses(player.shortName)">
8          <h4>{{player.name}}</h4>
9          <p>{{player.goals}} goals</p>
10          <p>{{player.assists}} assists</p>
11        </li>
12      </ul>
13    </div>

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 code snippet above, don’t panic yet, we’ll define them in our component file below.

Styling

1// app.component.scss
2    
3    div {
4      width: 60%;
5      margin: auto;
6      text-align: center;
7      ul {
8        list-style: none;
9        padding-left: 0;
10        display: flex;
11        justify-content: center;
12        li {
13          padding: 20px;
14          img {
15            width: 100px;
16            height: 100px;
17            border-radius: 50%;
18            box-shadow: 0 3px 4px 1px rgba(0, 0, 0, 0.1);
19            filter: grayscale(1);
20            border: 4px solid rgba(0, 0, 0, 0.2);
21            cursor: pointer;
22            &.elect {
23              border: 3px solid rgb(204, 54, 54);
24              box-shadow: 0 4px 7px 1px rgba(0, 0, 0, 0.1);
25              filter: grayscale(0);
26              cursor: default;
27            }
28            &.lost {
29              box-shadow: unset;
30              border: 4px solid rgba(0, 0, 0, 0.1);
31              &:hover {
32                filter: grayscale(1);
33                cursor: default;
34              }
35            }
36            &:hover {
37              filter: grayscale(0);
38            }
39          }
40          h4 {
41            font-size: 16px;
42            opacity: 0.9;
43            margin-bottom: 8px;
44            font-weight: lighter;
45          }
46          p {
47            font-size: 14px;
48            opacity: 0.6;
49            font-weight: bold;
50            margin: 4px 0;
51          }
52        }
53      }
54    }

These styles are meant to add a bit of life to our application. It also helps distinguish between states during application use. For example: the voted player is highlighted with a red border

App component

In the HTML snippet we made reference to some variables that weren’t yet defined, we’ll create the variables here with the logic behind our application.

1// app.component.ts
2    
3    import { Component, OnInit } from '@angular/core';
4    import { HttpClient } from '@angular/common/http';
5    
6    @Component({
7      selector: 'app-root',
8      templateUrl: './app.component.html',
9      styleUrls: ['./app.component.scss'],
10    })
11    export class AppComponent implements OnInit {
12      constructor(private http: HttpClient) {}
13      event = 'vote';
14      vote = '';
15      voted = false;
16      playerData = [
17        {
18          name: 'Mo. Salah',
19          goals: 30,
20          assists: 12,
21          shortName: 'salah',
22          image: 'https://platform-static-files.s3.amazonaws.com/premierleague/photos/players/250x250/p118748.png'
23        },
24        {
25          name: 'Christian Eriksen',
26          goals: 8,
27          assists: 13,
28          shortName: 'eriksen',
29          image: 'https://platform-static-files.s3.amazonaws.com/premierleague/photos/players/250x250/p80607.png',
30        },
31        {
32          name: 'Harry Kane',
33          goals: 26,
34          assists: 5,
35          shortName: 'kane',
36          image:
37            'https://platform-static-files.s3.amazonaws.com/premierleague/photos/players/40x40/p78830.png',
38        },
39        {
40          name: "Kevin De'bruyne",
41          goals: 10,
42          assists: 17,
43          shortName: 'kevin',
44          image: 'https://platform-static-files.s3.amazonaws.com/premierleague/photos/players/40x40/p61366.png',
45        },
46      ];
47      voteCount = {
48        salah: 0,
49        kane: 0,
50        eriksen: 0,
51        kevin: 0,
52      };
53      
54      castVote(player) {
55        this.http
56          .post(`http://localhost:4000/vote`, { player })
57          .subscribe((res: any) => {
58            this.vote = res.player;
59            this.voted = true;
60          });
61      }
62      
63      getVoteClasses(player) {
64        return {
65          elect: this.voted && this.vote === player,
66          lost: this.voted && this.vote !== player,
67        };
68      }
69      
70      ngOnInit() {
71      }
72    }
  • castVote: 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:

1// app.module.ts
2    import { BrowserModule } from '@angular/platform-browser';
3    import { NgModule } from '@angular/core';
4    import { AppComponent } from './app.component';
5    import {HttpClientModule} from '@angular/common/http';
6    
7    ....
8    @NgModule({
9      declarations: [AppComponent],
10      imports: [BrowserModule, HttpClientModule],
11      providers: [],
12      bootstrap: [AppComponent],
13    })
14      ....

By now our application should look like this:

angular-football-poll-stage-1

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 these problems, we’ll include the Pusher library and Chart.js for data visualization.

Open a terminal in the root folder of the project and install these packages by running the following command:

npm install pusher-js chart.js ng2-charts

To make both libraries available in our project we’ll add the libraries as third party scripts to be loaded by Angular CLI. All CLI config is stored in .angular-cli.json file. Modify the scripts property to include the link to pusher.min.js. and chart.js files.

1// .angular-cli.json
2    ...
3    
4    "scripts": [
5      "../node_modules/pusher-js/dist/web/pusher.min.js",
6      "../node_modules/chart.js/src/chart.js"
7    ]
8     ...

After updating this file, you’ll need to restart the angular server so that the CLI compiles the new script files we’ve just added.

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

ng generate service pusher

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

1// pusher.service.ts
2    
3    import { Injectable } from '@angular/core';
4    
5    declare const Pusher: any;
6    
7    @Injectable()
8    export class PusherService {
9      constructor() {
10        var pusher = new Pusher('<PUSHER_KEY>', {
11          cluster: 'eu',
12          encrypted: true,
13        });
14        this.channel = pusher.subscribe('vote-channel');
15      }
16      channel;
17      
18      public init() {
19        return this.channel;
20      }
21    }
  • 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 service available application wide, import it into the module file.

1// app.module.ts
2    import {PusherService} from './pusher.service'
3    ...
4    
5    @NgModule({
6       ....
7       providers: [PusherService],
8       ....
9     })

We’ll make use of this service in our component, by binding to the vote event and incrementing the votes of the voted player returned in the event. This will be done in the ngOnInit lifecycle.

1// app.component.ts
2    import { Component, OnInit } from '@angular/core';
3    import { HttpClient } from '@angular/common/http';
4    import { PusherService } from './pusher.service';
5    
6    @Component({
7      selector: 'app-root',
8      templateUrl: './app.component.html',
9      styleUrls: ['./app.component.scss'],
10    })
11    export class AppComponent implements OnInit {
12      constructor(private pusher: PusherService, private http: HttpClient) {}
13      ...
14      
15      ngOnInit() {
16        const channel = this.pusher.init();
17        channel.bind('vote', ({ player }) => {
18          this.voteCount[player] += 1;
19        });
20      }
21    }

Data visualization

Now that our application has been built out, we’ll need to visualize the voting process using charts. This is vital because we need a way to determine the winner of the polls and how each person voted.

To make use of charts in our application, we’ll import the ChartsModule into our app.module.ts file.

1// app.module.ts
2    import {ChartsModule} from 'ng2-Charts';
3    ....
4    
5    @NgModule({
6      declarations: [AppComponent],
7      imports: [BrowserModule, HttpClientModule, ChartsModule],
8      providers: [PusherService],
9      bootstrap: [AppComponent],
10    })
11      ....

We can then use the canvas component to provide visualization. Make the following changes to your app.component.ts, html and css files.

1// app.component.ts
2    ...
3    
4    playerData = [
5        {
6          name: 'Mo. Salah',
7          goals: 30,
8          assists: 12,
9          shortName: 'salah',
10          image:
11            'https://platform-static-files.s3.amazonaws.com/premierleague/photos/players/250x250/p118748.png',
12        }
13        ...
14      ];
15     voteCount = {
16        salah: 0,
17        kane: 0,
18        eriksen: 0,
19        kevin: 0,
20      };
21     chartLabels: string[] = Object.keys(this.voteCount);
22     chartData: number[] = Object.values(this.voteCount);
23     chartType = 'doughnut';
24    
25     ...
26     
27     ngOnInit() {
28        const channel = this.pusher.init();
29        channel.bind('vote', ({ player }) => {
30          this.voteCount[player] += 1;
31          // Update the chartData whenever there's a new vote
32          this.chartData = Object.values(this.voteCount);
33        });
34       }
35     }

chartLabels: we provide labels for our chart using the keys of the voteCount object. chartData: the chart data will make use of the values of the voteCount object which signifies the vote count of each player. chartType: we specify the chart type we’ll use.

We also made a few changes to the ngOnInit lifecycle. We update the chartData values whenever there’s a new vote event.

1// app.component.html
2    
3    <div>
4        ...
5        </li>
6      </ul>
7      
8      <div class="chart-box" *ngIf="voted">
9        <h2>How others voted</h2>
10        <canvas baseChart [data]="chartData"
11        [labels]="chartLabels" [chartType]="chartType">
12        </canvas>
13      </div>
14    </div>
15
16
17    // app.component.scss
18    ...
19    
20    .chart-box{
21      display: flex;
22      flex-direction: column;
23      justify-content: center;
24    }

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

angular-football-poll-complete

To test the realtime functionality of the application, open two browsers side-by-side and place votes. You’ll notice that votes placed on one reflect on the other browser.

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.