Push Notifications Using Angular In Browser

In today’s web-based application development, one of the main features is information notification. Because people today have a tough time to remember any things like a task, to do work etc. Notifications process or mechanism always helps people to deliver information on time and remind the people about their pending tasks. A recent study on mobile users stated that mobile users receive an average of 63 notifications per day, out of this notification most of coming from messaging or email applications.

In today’s web-based application development, one of the main features is information notification; because people, today, have a tough time to remember any things like a task, to do work etc. Notifications process or mechanism always helps people to deliver information on time and remind the people about their pending tasks. A recent study on mobile users stated that mobile users receive an average of 63 notifications per day, out of this notification most of coming from messaging or email applications.

About Push Notifications

Push notifications are basically are one type of service which is used for displaying alert information to the users. This service will throw alert message which user want to see at a particular time from any particular apps or services. These messages can come from any source of media like SMS service, email Service or custom service defined by the application itself.

Sometimes, push notifications also known as server push notifications. This is called because push notification is delivered any information from an application on a device without any specific request from the client end. Basically, this is the basic difference between pull notifications and push notifications. In case of pull notifications, the client must send a request to the server for the information whereas in case of push notification server send the information to the client without receiving any request from the client end. Actually, the end user must opt-in to receive alerts and end-user need to accept that setting during the installation of the application or at the startup of the application.

What is Push Notifications

A notification always displays a message that pops up on the user’s device screen. This notification can be triggered locally by any application which is running or they can push the notification information fetched from the server to the user device when the application is not running. This will engage the user to get the information on time and does not need to remember the information. Push notifications mainly depend on the Two APIs – Notification APIs and Push APIs. The Notifications API let the application display notification information to the user screen. The Push API always allows a service worker process to fetch the push message from the server even when the application is not active.

Different Types of Notifications

In general, there are three different types of notifications normally available. They are,

  1. Transactional Notifications
    Basically, Transactional Notifications are normally used to notify the user about any particular events like notifying a user that a package has been sending to the shipment for the delivery which user order it.

  2. System Notifications
    This type of notifications is used to inform the user about the new features of the product or any items or any special offer like notify the user about a special discount that announced on purchase any such item on any particular holiday dates.

  3. User Notifications
    This type of notifications is used to notify the user about the new messages from their friends or other sources like emails or social networking message or application based custom message.
How Web Push Works

Each and every browser manage push notification through their own systems, which is normally called as Push Service. First of all, the user needs to grant permission for Push Notification on that site, by accepting that permission user can subscribe the application to the browser push service. This creates a special subscription object that contains the "endpoint URL" of the push service, which is different for each browser and a public key. We send our push messages to this URL, and the push service sends it to the right client in the browser.
 
Now, for implementing this concept in Angular4, we need to develop one angular component which contains a button on click of this button push notification will be appeared in the browser and also we need to develop one Angular 4 services which will responsible for the pop the push notification messages.

Sample Code of push-notification.service.ts
  1. import {  
  2.     Injectable  
  3. } from '@angular/core';  
  4. import {  
  5.     Observable  
  6. } from 'rxjs/Observable';  
  7. @Injectable()  
  8. export class PushNotificationsService {  
  9.     public permission: Permission;  
  10.     constructor() {  
  11.         this.permission = this.isSupported() ? 'default' : 'denied';  
  12.     }  
  13.     public isSupported(): boolean {  
  14.         return 'Notification' in window;  
  15.     }  
  16.     requestPermission(): void {  
  17.         let self = this;  
  18.         if ('Notification' in window) {  
  19.             Notification.requestPermission(function(status) {  
  20.                 return self.permission = status;  
  21.             });  
  22.         }  
  23.     }  
  24.     create(title: string, options ? : PushNotification): any {  
  25.         let self = this;  
  26.         return new Observable(function(obs) {  
  27.             if (!('Notification' in window)) {  
  28.                 console.log('Notifications are not available in this environment');  
  29.                 obs.complete();  
  30.             }  
  31.             if (self.permission !== 'granted') {  
  32.                 console.log("The user hasn't granted you permission to send push notifications");  
  33.                 obs.complete();  
  34.             }  
  35.             let _notify = new Notification(title, options);  
  36.             _notify.onshow = function(e) {  
  37.                 return obs.next({  
  38.                     notification: _notify,  
  39.                     event: e  
  40.                 });  
  41.             };  
  42.             _notify.onclick = function(e) {  
  43.                 return obs.next({  
  44.                     notification: _notify,  
  45.                     event: e  
  46.                 });  
  47.             };  
  48.             _notify.onerror = function(e) {  
  49.                 return obs.error({  
  50.                     notification: _notify,  
  51.                     event: e  
  52.                 });  
  53.             };  
  54.             _notify.onclose = function() {  
  55.                 return obs.complete();  
  56.             };  
  57.         });  
  58.     }  
  59.     generateNotification(source: Array < any > ): void {  
  60.         let self = this;  
  61.         source.forEach((item) => {  
  62.             let options = {  
  63.                 body: item.alertContent,  
  64.                 icon: "../resource/images/bell-icon.png"  
  65.             };  
  66.             let notify = self.create(item.title, options).subscribe();  
  67.         })  
  68.     }  
  69. }  
  70. export declare type Permission = 'denied' | 'granted' | 'default';  
  71. export interface PushNotification {  
  72.     body ? : string;  
  73.     icon ? : string;  
  74.     tag ? : string;  
  75.     data ? : any;  
  76.     renotify ? : boolean;  
  77.     silent ? : boolean;  
  78.     sound ? : string;  
  79.     noscreen ? : boolean;  
  80.     sticky ? : boolean;  
  81.     dir ? : 'auto' | 'ltr' | 'rtl';  
  82.     lang ? : string;  
  83.     vibrate ? : number[];  
  84. }  
The Above push notification service contains the following members,
  1. isSupported()
    Basically this a public method which basically returns the notification windows.

  2. requestPermission()
    This method is performed to create the browser pops settings at the loading time of the application. If a user grants the permission of the push notification pops, the next message will be pop the notification message. If the user denied the permission, then it will not ask again for the permission.

  3. generateNotification()
    This public method exposed to the outer world or application so that anybody can access this method and send the message contains as an array of a message to this message. One this method executed, it will create the push notification alerts and pops into the browser.

  4. create()
    This method is used to create the push notification message for the browser.
Sample code of app.component.pushnotification.ts
  1. import {  
  2.     Component,  
  3.     OnInit,  
  4.     EventEmitter,  
  5.     Output  
  6. } from '@angular/core';  
  7. import {  
  8.     PushNotificationsService  
  9. } from './push-notifications.service';  
  10. @Component({  
  11.     moduleId: module.id,  
  12.     selector: 'push-notification',  
  13.     templateUrl: 'app.component.pushnotification.html',  
  14. })  
  15. export class PushNotificationComponent implements OnInit {  
  16.     private title: string = 'Browser Push Notifications!';  
  17.     constructor(private _notificationService: PushNotificationsService) {  
  18.         this._notificationService.requestPermission();  
  19.     }  
  20.     ngOnInit() {}  
  21.     notify() {  
  22.         let data: Array < any >= [];  
  23.         data.push({  
  24.             'title''Approval',  
  25.             'alertContent''This is First Alert -- By Debasis Saha'  
  26.         });  
  27.         data.push({  
  28.             'title''Request',  
  29.             'alertContent''This is Second Alert -- By Debasis Saha'  
  30.         });  
  31.         data.push({  
  32.             'title''Leave Application',  
  33.             'alertContent''This is Third Alert -- By Debasis Saha'  
  34.         });  
  35.         data.push({  
  36.             'title''Approval',  
  37.             'alertContent''This is Fourth Alert -- By Debasis Saha'  
  38.         });  
  39.         data.push({  
  40.             'title''To Do Task',  
  41.             'alertContent''This is Fifth Alert -- By Debasis Saha'  
  42.         });  
  43.         this._notificationService.generateNotification(data);  
  44.     }  
  45. }  
Sample Code of App.component.pushnotification.html
  1. <div class="container">  
  2.     <h1> {{title}} </h1>   
  3.     <button (click)="notify()">Show Notiication</button>   
  4. </div> 
 The output is below.

 

At the loading time of the application, requestPermission() method execute from the constructor of the component and it will ask for permission from the users.

Once the user approves this permission, the next result will as be below when notification message fired.