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.
-
Cloud ServicesGet Started With Pusher: Introducing Channels
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.
npm install -g @angular/cli
Next, use Angular CLI to create the Angular app.
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.
{{ title }}!
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.
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.
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.
{{claps}}
Adding Pusher to Your App
We will first need to install the Pusher library with the npm install
command.
npm install --save pusher-js
Next, load the Pusher Library by adding the following script in the angular.json
file.
//angular.json "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:
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:
// app.module.ts import { PusherService } from './pusher.service'; ... @NgModule({ providers: [PusherService], ... })
Angular also provides an environment file for storing credentials for security purposes: include your pusher key in environment.ts.
// environment.ts export const environment = { pusher: { production: false, key: '', } };
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:
// pusher.service.ts import { environment } from '../environment/environment'; declare const Pusher: any; export class PusherService { pusher: any; constructor() { this.pusher = new Pusher(environment.pusher.key); } }
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:
declare const Pusher: any; import { Injectable } from '@angular/core'; import { environment } from '../environments/environment'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class PusherService { pusher: any; channel: any; constructor(private http: HttpClient) { this.pusher = new Pusher(environment.pusher.key); this.channel = this.pusher.subscribe('my_channel'); } }
Next, create a function that sends the number of claps to the server when the applause button is clicked.
// pusher.service.ts export class PusherService { // ... clap( claps_count ) { this.http.get(`http://localhost:3000/add/${claps_count}`) .subscribe(); } }
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.
import { PusherService } from './pusher.service'; //... export class AppComponent implements OnInit { title = 'Pusher Realtime Notifications'; claps: any = 0; // Listen to click event and send claps increment to server Applause() { this.claps = parseInt(this.claps, 10) + 1; this.pusherService.clap( this.claps ); } constructor(private pusherService: PusherService) { } ngOnInit() { this.pusherService.channel.bind('new-event', data => { this.claps = data.claps ; }); } }
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.
mkdir server cd server npm init
This creates all the necessary files to bootstrap a Node.js application. Next, install the Pusher, Express, and body-parser modules.
npm install --save pusher express body-parser
Next, create a file index.js and import all the required modules:
const express = require('express'); const http = require('http'); const bodyParser = require('body-parser'); const port = process.env.PORT || '3000'; const app = express(); 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.
const pusher = new Pusher({ appId: '607521', key: 'e9f68f905ee8a22675fa', secret: '37ab37aac91d180050c2', });
Define middleware, CORS headers, and the rest of the Node application configurations.
// define middleware 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(); }); // Define routes app.set('port', port); const server = http.createServer(app); 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.
//server.js ..... app.get("/add/:claps",function(req, res) { pusher.trigger("my_channel", "new-event", { }); });
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.
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.
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.
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.
Powered by WPeMatico