Advertisement
  1. Code
  2. Cloud & Hosting

How to Build Medium's Real-Time Applause Feature With Angular and Pusher

Scroll to top

In this article, you'll learn how to code real-time Angular apps with Pusher. We'll make an app that gives real-time feedback when a post is clicked—just like Medium's applause feature!

What Is Pusher?

Pusher is a service that provides developers with APIs which enable them to integrate real-time functionalities in web, mobile, and back-end applications. To learn more about Pusher, check out this tutorial video for an introduction.

Getting Started With Pusher in Angular

As mentioned at the beginning of this tutorial, our app will give real-time feedback whenever someone clicks a post. 

For starters, make sure you have Node and npm installed on your machine. You'll also need Angular CLI to quickly bootstrap our app, so make sure you have it installed as well. If you don't have Angular CLI installed, simply issue the following command.

1
npm install -g @angular/cli

Next, use Angular CLI to create the Angular app.

1
ng new pusher-angular

The UI of our app will be very simple. It will have a post, an applause button which will be represented by a hand icon, and a counter of the number of claps the post has garnered. Open app.component.html and add the following code, in which we tie the click event to the Applause() function.

1
<div align="center">
2
  <h1>
3
    {{ title }}!
4
  </h1>
5
  <p>This article will show how to implement real-time functionality in Angular Applications using Pusher. We will make an application that gives real-time feedback when a post is clicked. The application will mainly focus on adding real-time functionality to the Angular application.</p>
6
7
<p>Real-time functionality is an important component in modern applications. Users want immediate feedback when interacting with applications. This has prompted many developers to consider inclusion of this functionality due to tremendous demand.</p>
8
9
<h3>What Is Pusher?</h3>
10
<p>Pusher is a service that provides developers with APIs which enable them to integrate real-time functionalities in web, mobile, and back-end applications.</p>
11
12
  <div div align="center">
13
      <h3>{{claps}}</h3>
14
  <img width="30" alt="medium Applause" (click)="Applause()" src="../assets/download.png" />
15
    
16
  </div>
17
</div>

Adding Pusher to Your App

We will first need to install the Pusher library with the npm install command. 

1
npm install --save pusher-js

Next, load the Pusher Library by adding the following script in the angular.json file.

1
//angular.json
2
3
"scripts": ["../node_modules/pusher-js/dist/web/pusher.min.js"]

You will also need to have Pusher credentials, which can be obtained from the Pusher dashboard.

To obtain the credentials, log in to the Pusher dashboard and click Create new app. You will then fill out some details about your application and finally click on Create my app. Pusher also gives you some code to get started according to the technology you have chosen. The most important aspect of this process is the app credentials, which can be found on the App Keys tab.

Integrate the Pusher Service

We will then create our PusherService by running the command:

1
ng generate service Pusher

The above command will create two files, namely pusher.service.ts and pusher.service.spec.ts, which contain some boilerplate code to get started

Now import the service in the main module and include it as a provider as follows:

1
// app.module.ts

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

Angular also provides an environment file for storing credentials for security purposes: include your pusher key in environment.ts.

1
// environment.ts

2
export const environment = {
3
  pusher: {
4
    production: false,
5
    key: '<PUSHER_KEY>',
6
  }
7
};

Next, import the environment module for use, declare Pusher as an import from the script we added earlier in angular.json, and declare a Pusher constant in the PusherService file as follows:

1
// pusher.service.ts

2
import { environment } from '../environment/environment';
3
declare const Pusher: any;
4
5
export class PusherService {
6
pusher: any;
7
8
  constructor() {
9
  this.pusher = new Pusher(environment.pusher.key);
10
   }
11
}

We want to make a request containing the number of claps to the server whenever a person likes a post and also subscribe to our Pusher channel. Go ahead and include the HttpClient in the constructor of the PusherService. Your pusher.service file should now look like this:

1
declare const Pusher: any;
2
import { Injectable } from '@angular/core';
3
import { environment } from '../environments/environment';
4
import { HttpClient } from '@angular/common/http';
5
6
@Injectable({
7
  providedIn: 'root'
8
})
9
10
export class PusherService {
11
  pusher: any;
12
  channel: any;
13
  constructor(private https: HttpClient) {
14
    this.pusher = new Pusher(environment.pusher.key);
15
    this.channel = this.pusher.subscribe('my_channel');
16
  }
17
}

Next, create a function that sends the number of claps to the server when the applause button is clicked.

1
// pusher.service.ts

2
export class PusherService {
3
// ...

4
clap( claps_count ) {
5
    this.http.get(`http://localhost:3000/add/${claps_count}`)
6
    .subscribe();
7
  }
8
}

Still on the client side, we will write a function that listens for click events from the angular application and increments the number of claps. We will also bind the Pusher service to our event.

1
import { PusherService } from './pusher.service';
2
//...

3
export class AppComponent implements OnInit {
4
  title = 'Pusher Realtime Notifications';
5
  claps: any =  0;
6
  
7
  // Listen to click event and send claps increment to server

8
  Applause() {
9
    this.claps = parseInt(this.claps, 10) + 1;
10
    this.pusherService.clap( this.claps );
11
  }
12
13
  constructor(private pusherService: PusherService) {
14
  }
15
16
  ngOnInit() {
17
    this.pusherService.channel.bind('new-event', data => {
18
      this.claps = data.claps ;
19
    });
20
  }
21
}

Building the Node.js Server

A server will be used to receive the data requests from the Angular app—we'll build it using Express, a simple and fast Node.js framework.

Create a directory named server, and run the following commands.

1
mkdir server
2
cd server
3
npm init

This creates all the necessary files to bootstrap a Node.js application. Next, install the Pusher, Express, and body-parser modules.

1
 npm install --save  pusher express body-parser 

Next, create a file index.js and import all the required modules:

1
const express = require('express');
2
const http = require('http');
3
const bodyParser = require('body-parser');
4
const port = process.env.PORT || '3000';
5
const app = express();
6
const Pusher = require('pusher');

The next step is to initialize Pusher by instantiating Pusher with the necessary credentials. You can obtain the credentials from the Pusher dashboard.

1
const pusher = new Pusher({
2
  appId: '607521',
3
  key: 'e9f68f905ee8a22675fa',
4
  secret: '37ab37aac91d180050c2',
5
});

Define middleware, CORS headers, and the rest of the Node application configurations.

1
// define middleware

2
app.use(bodyParser.json());
3
app.use(bodyParser.urlencoded({ extended: false }));
4
app.use((req, res, next) => {
5
  res.header("Access-Control-Allow-Origin", "*")
6
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
7
  next();
8
});
9
10
// Define routes

11
12
app.set('port', port);
13
const server = http.createServer(app);
14
server.listen(port, () => console.log(`Running on port ${port}`));

We will then create the endpoint that will listen to any incoming requests from our Angular app. The endpoint will get the number of claps from the client and then trigger a messaging event.

1
//server.js
2
.....
3
app.get("/add/:claps",function(req, res) {
4
    pusher.trigger("my_channel", "new-event", {
5
    });
6
});

Our server is now complete; you can start listening to incoming subscriptions by running npm start.

Testing Our App

Now run the client and server at the same time by issuing ng serve for the Angular app and npm start for the Express Server.

Ensure you have enabled client events on the Pusher dashboard, as shown below.

Enable Client eventsEnable Client eventsEnable Client events

Navigate to http://localhost:4200 and start interacting with the app by clicking on the applause button. Ensure you have two tabs side by side so that you can observe in real time how the number of claps increases when a post is liked.

Real time PusherReal time PusherReal time Pusher

Another cool feature of Pusher is that you can view all the connections and messages sent by using the dashboard. Here's a screenshot of the dashboard for this app.

Pusher ActivityPusher ActivityPusher Activity

Conclusion

As you have seen, it's very easy to integrate Pusher with an Angular app. This makes it possible to add functionality like real-time data sharing and push notifications to your app.

Pusher is also available for different platforms, so head over to the site and discover the magic of Pusher.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.