Making Angular 5 realtime with WebSockets
A basic understanding of Angular 5 and Node.js is needed to follow this tutorial.
The demand for realtime functionality in applications these days has grown tremendously. People want to see how users interact with their applications in realtime. Here comes Pusher, allowing you to add realtime functionality to your application by using concepts such as events and channels. In this article, we are going to look at how to add realtime functionality to your Angular 5 application.
Introduction
We are going to make an application that gives realtime feedback when a picture is liked. In other words, you get to see in realtime when users like a picture - interesting, right? To do this, we will be using Angular 5 and Pusher API.
Getting started
To get started, you need to make sure your have Node and NPM installed on your machine. You can confirm you installation by running:
npm --version
node --version
If you get version numbers as results then you have them installed. Node 6+ and NPM 4+ should be your target.
Building the Angular 5 application
Now we are not going to dwell too much on the intricacies of building an Angular application, rather, we will be more concerned about adding realtime functionality to the application itself.
To create your Angular application, you need to ensure that you have Angular 5 installed on your machine. You can confirm your installation by running:
ng --version
If you don’t have Angular installed or your version is less than 1.2, run this command in your terminal:
npm install -g @angular/cli
For more information about Angular basics, head here.
We can now create our application by running:
ng new angular5-pusher
After running this, we get a basic Angular starter project which we are going to build upon.
App component
Now the view of the application is pretty simple. We have an image, a button to like the image and the count of images that have been liked. The app.component.html
file looks like this:
<div class="main-app">
<h1>
{{ title }}!
</h1>
<img width="300" alt="Pusher Logo" src="../assets/pusher.svg" />
<div class="like">
<div style="margin-right: 1rem">
<h2>{{ likes }} likes</h2>
</div>
<button class="btn btn-lg btn-success" (click)="liked()">Like Image</button>
</div>
</div>
We can see from the above that the buttonClick
event has been tied to a function called liked()
which we will take a look at now.
In our app.component.ts
file, we have the following:
import { Component, OnInit } from '@angular/core';
//..
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Pusher Liker';
likes: any = 10;
constructor() {
// the pusher service will be injected as part of the constructor later
}
ngOnInit() {
// ..
}
// add to the number of likes to the server
liked() {
this.likes = parseInt(this.likes, 10) + 1;
// ..
}
}
Now we can see when we examine the component that we specify the title
and the number of likes
for starters.
NB: In a real world application, you will want to make a request to your backend server to get the actual number of likes instead of using static data.
We can also see that we plan on injecting a pusherService
in the constructor of our app component. We are going to explain more about this in the next section.
Adding Pusher to your application
At this point, we have our application that allows us to like pictures, but other users don’t get realtime feedback as to the number of likes the picture actually has. In comes Pusher to save the day. Pusher allows you to add realtime functionality to your application without you having to stress so much about the logic of making this work.
All you need to do is to subscribe
to a channel and then listen
for events
- in simpler terms it’s like turning on a TV to a football match (channel ) and then waiting for a team to score a goal ( event ).
Now lets see how to add this to our existing Pusher Liker Application .To use Pusher with Angular, we first need to install and load Pusher’s client library:
npm install --save pusher-js
Now that we have successfully installed the library, the next thing we need to do is to add it as one of the third party scripts that will be loaded by Angular when our page is being loaded.
In the .angular-cli.json
we include the following:
//...
"scripts": ["../node_modules/pusher-js/dist/web/pusher.min.js"]
//...
Now lets get to using the pusher client.
Earlier on, we spoke about the PusherService
and now we are going to see how it works. In angular, there is a concept called services
- which, as the name suggests, helps you to do one thing really well.
We create our PusherService
by running the command:
ng generate service Pusher
This creates the pusher.service.ts
and pusher.service.spec.``ts
files. We are only going to be concerned with the pusher.service.ts
At he top of the pusher.service.``ts
file we declare our Pusher constant so that Angular knows that we know what we are doing, and we are going to use the Pusher
class from an external script which we loaded earlier:
// pusher.service.ts
declare const Pusher: any;
// ...
Then, we import the necessary classes we are going to need:
// .... pusher.service.ts
import { Injectable } from '@angular/core';
import { environment } from '../environments/environment';
import { HttpClient } from '@angular/common/http';
// .....
If you used older versions of Angular, the new HttpClient
may seem strange to you because it was just introduced with this new version to make life easier for Angular developers. With this new HttpClient
, responses are defaulted to JSON
and interceptors are now being used for easier error handling. You can read more about it here.
We also included the environment
class, which contains some enviroment variables for pusher to work. The enviroment.ts
file looks like this:
// ... environment.ts
export const environment = {
production: false,
pusher: {
key: 'PUSHER_API_KEY',
cluster: 'PUSHER_CLUSTER',
}
};
These details can be obtained from your Pusher app dashboard.
To create a new app:
- Click “Create New App” from the left sidebar.
- Configure an app by providing basic information requested in the form presented. You can also choose the environment you intend to integrate Pusher with for a better setup experience:
Now, back to our pusher.service.``ts
file:
//...pusher.service.ts
@Injectable()
export class PusherService {
pusher: any;
channel: any;
constructor(private http: HttpClient) {
this.pusher = new Pusher(environment.pusher.key, {
cluster: environment.pusher.cluster,
encrypted: true
});
this.channel = this.pusher.subscribe('events-channel');
}
like( num_likes ) {
his.http.post('http://localhost:3120/update', {'likes': num_likes})
.subscribe(data => {});
}
}
In the constructor for the PusherService
, we included the HttpClient
and then subscribed
to the events-channel
. We also have another function that makes a POST
request to our backend server with the number of likes as part of the body
of the request when the like
button is clicked.
NB : The implementation details of our backend server will be built later in the article
Now we will go back to our app.component.``ts
file to see how we factor in the new Pusher service:
//-- app.component.ts
import { Component, OnInit } from '@angular/core';
import { PusherService } from './pusher.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Pusher Liker';
likes: any = 10;
constructor(private pusherService: PusherService) {
}
ngOnInit() {
this.pusherService.channel.bind('new-like', data => {
this.likes = data.likes ;
});
}
// add to the number of likes to the server
liked() {
this.likes = parseInt(this.likes, 10) + 1;
this.pusherService.like( this.likes );
}
}
In the above, we import the pusherService
and then add it to our constructor. Now, when the component is created, we then bind the pusherService
to the new-like
event and we update the number of likes with the new number of likes that we get.
Now you may be wondering, “it’s cool that we can now tell when the number of likes have increased and the update them, but what when someone actually clicks the button, what triggers the event?”
As we can see in the liked()
function above, the pusherService.like()
is also called to help make the request to the backend server to actually trigger the like event.
Now that our front-end is ready, we can run the application by running:
npm start
Building the backend Server
Now, we’ll take a quick look at the backend server that triggers the event and how it works. In the project directory we create a folder called server
and in there is where we do all the work:
mkdir server
In the server
directory, we run:
npm init
And then we install the necessary modules we are going to need:
npm install --save cors pusher express body-parser dotenv
Once that’s done, we can now create our server.js
in the same directory
In our server.js
file, we do the following:
Import Node modules
// -------------------------------
// Import Node Modules
// -------------------------------
require("dotenv").config();
const cors = require("cors");
const Pusher = require("pusher");
const express = require("express");
const bodyParser = require("body-parser");
Create app and load Middlewares
// ------------------------------
// Create express app
// ------------------------------
const app = express();
// ------------------------------
// Load the middlewares
// ------------------------------
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Create Pusher client
// ....
const pusher = new Pusher({
appId: `${process.env.PUSHER_APP_ID}`,
key: `${process.env.PUSHER_API_KEY}`,
secret: `${process.env.PUSHER_API_SECRET}`,
cluster: `${process.env.PUSHER_APP_CLUSTER}`,
encrypted: true
});
Now add a .env
file at the root of the server
folder with the following lines:
PUSHER_APP_ID=[PUSHER_APP_ID]
PUSHER_API_KEY=[PUSHER_API_KEY]
PUSHER_API_SECRET=[PUSHER_API_SECRET]
PUSHER_APP_CLUSTER=[PUSHER_APP_CLUSTER]
These details for the Pusher client can be obtained from your Pusher dashboard.
Create application routes
// -------------------------------
// Create app routes
// -------------------------------
app.post("/update", function(req, res) {
// -------------------------------
// Trigger pusher event
// ------------------------------
pusher.trigger("events-channel", "new-like", {
likes : `${req.body.likes}`
});
});
This application only has one route that triggers the new-like
event to the events-channel
which our Angular frontend listens for and then updates accordingly.
Assign application
app.listen("3120");
console.log("Listening on localhost:3120");
Now, the backend server will be run at localhost:3120
.
Conclusion
In this article we have seen how to add realtime functionality to an Angular 5 application. The use cases for this are endless. You can give users realtime feedback as they interact with your applications — Twitter has a feature similar to this where you can actually see the number of likes, replies and retweets in realtime.
The ball is in your court now to implement that realtime feature you know your users will love to have.
23 February 2018
by Christian Nwamba