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,
- 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.
- 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.
- 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
- import {
- Injectable
- } from '@angular/core';
- import {
- Observable
- } from 'rxjs/Observable';
- @Injectable()
- export class PushNotificationsService {
- public permission: Permission;
- constructor() {
- this.permission = this.isSupported() ? 'default' : 'denied';
- }
- public isSupported(): boolean {
- return 'Notification' in window;
- }
- requestPermission(): void {
- let self = this;
- if ('Notification' in window) {
- Notification.requestPermission(function(status) {
- return self.permission = status;
- });
- }
- }
- create(title: string, options ? : PushNotification): any {
- let self = this;
- return new Observable(function(obs) {
- if (!('Notification' in window)) {
- console.log('Notifications are not available in this environment');
- obs.complete();
- }
- if (self.permission !== 'granted') {
- console.log("The user hasn't granted you permission to send push notifications");
- obs.complete();
- }
- let _notify = new Notification(title, options);
- _notify.onshow = function(e) {
- return obs.next({
- notification: _notify,
- event: e
- });
- };
- _notify.onclick = function(e) {
- return obs.next({
- notification: _notify,
- event: e
- });
- };
- _notify.onerror = function(e) {
- return obs.error({
- notification: _notify,
- event: e
- });
- };
- _notify.onclose = function() {
- return obs.complete();
- };
- });
- }
- generateNotification(source: Array < any > ): void {
- let self = this;
- source.forEach((item) => {
- let options = {
- body: item.alertContent,
- icon: "../resource/images/bell-icon.png"
- };
- let notify = self.create(item.title, options).subscribe();
- })
- }
- }
- export declare type Permission = 'denied' | 'granted' | 'default';
- export interface PushNotification {
- body ? : string;
- icon ? : string;
- tag ? : string;
- data ? : any;
- renotify ? : boolean;
- silent ? : boolean;
- sound ? : string;
- noscreen ? : boolean;
- sticky ? : boolean;
- dir ? : 'auto' | 'ltr' | 'rtl';
- lang ? : string;
- vibrate ? : number[];
- }
The Above push notification service contains the following members,
- isSupported()
Basically this a public method which basically returns the notification windows.
- 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.
- 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.
- create()
This method is used to create the push notification message for the browser.
Sample code of app.component.pushnotification.ts
- import {
- Component,
- OnInit,
- EventEmitter,
- Output
- } from '@angular/core';
- import {
- PushNotificationsService
- } from './push-notifications.service';
- @Component({
- moduleId: module.id,
- selector: 'push-notification',
- templateUrl: 'app.component.pushnotification.html',
- })
- export class PushNotificationComponent implements OnInit {
- private title: string = 'Browser Push Notifications!';
- constructor(private _notificationService: PushNotificationsService) {
- this._notificationService.requestPermission();
- }
- ngOnInit() {}
- notify() {
- let data: Array < any >= [];
- data.push({
- 'title': 'Approval',
- 'alertContent': 'This is First Alert -- By Debasis Saha'
- });
- data.push({
- 'title': 'Request',
- 'alertContent': 'This is Second Alert -- By Debasis Saha'
- });
- data.push({
- 'title': 'Leave Application',
- 'alertContent': 'This is Third Alert -- By Debasis Saha'
- });
- data.push({
- 'title': 'Approval',
- 'alertContent': 'This is Fourth Alert -- By Debasis Saha'
- });
- data.push({
- 'title': 'To Do Task',
- 'alertContent': 'This is Fifth Alert -- By Debasis Saha'
- });
- this._notificationService.generateNotification(data);
- }
- }
Sample Code of App.component.pushnotification.html
- <div class="container">
- <h1> {{title}} </h1>
- <button (click)="notify()">Show Notiication</button>
- </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.