Browser Push Notification in Angular 5
Remind your users of any pertinent notifications or changes in your application using this code compatible with Angular 5.
Join the DZone community and get the full member experience.
Join For FreeIn today’s web-based application development, one of the main features is information notification. 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, most coming from messaging or email applications.
About Push Notifications
Push notifications are basically one type of service used for displaying alert information to the users. This service will show alert messages 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, because push notifications are delivered 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: for pull notifications, the client must send a request to the server for the information, whereas push notification servers send 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 needs to accept that setting during the installation of the application or at the startup of the application.
Push notifications actually let our application extend beyond the browser and it is an excellent powerful way to engage or interact with the user. It basically performs a simple act, such as alerting the user about an important event, displaying an icon, or showing a small text message and then by clicking on that message users can be redirected to the related web site or applications.
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 so they get the information on time without having to remember it. 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 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 – Transactional notifications are normally used to notify the user about any particular events, like a package that has been sent to be shipped.
System Notifications – This type of notification is used to inform the user about the new features of the product or any items or special offers, such as a special discount on the purchase of a particular item.
User Notifications – This type of notification is used to notify the user about the new messages from their friends or other sources, like emails, social networking messages, application-based custom messages.
Push Notification Features
Push notifications must contain the following characteristics:
Notification – A message needs to display to the user application UI (i.e. in the browser)
Push Message – A message has to send from server to the client side without any request from the client end
Push Notification – A notification needs to be created in response to the push message
Notifications API – An interface or service layer needs to be configured to display the notification to the users.
Push Service – A process for the route of the push message from server end to the client end. Each browser has their own implementations to display push message.
How Web Push Works
Each and every browser manages push notification through their own systems, which is normally called a Push Service. First, the user needs to grant permission for Push Notifications 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.
To implement push notifications in the Angular framework, we need to develop an Angular service which actually performs the main work for populating the notification message in the browsers.
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[];
}
Now we need to develop an Angular component, which will invoke the above push notification service and send the message data to service so that notification can populate.
Sample code of app.component.pushnotifactions.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.pushnotifications.html
<div class="container">
<h1>
{{title}}
</h1>
<button (click)="notify()">Show Notiication</button>
</div>
Now add this component in the Angular module and execute in the browser. It will show the following output:
When the index.html page loaded, the browser asks the user to allow confirmation for push notifications to automatically populate when required.
The above code block of the notification is totally independent of any library. This code block will work on any Angular version 2 or above.
If you enjoyed this article and want to learn more about Angular, check out our compendium of tutorials and articles from JS to 8.
Opinions expressed by DZone contributors are their own.
Comments