In this tutorial, I am going to create a demo in which we will how to easily add browser push notifications to our Angular 2 applications.
Web Push notifications are a way to make you application more interactive and automatically push well tailored dynamic content to the target user. Earlier the push notification was possible to send on mobile only but now browsers have moved in to natively support this feature allowing web developers to integrate them with their web applications.
So lets start to create the demo
So for installing the module type the below command over terminal when a basic app is created by ng new web-push-app and app is browsable over link http://localhost:4200 after typing ng serve over terminal after app creation.
Now lets have a look on app.module.ts, We need to import the module and add it to the imports of our AppModule
In our AppComponent, we first import the PushNotificationsService. This service provides us with two useful methods.
requestPermission() – This method requests for permission from the user to show push notifications. The create() method which actually creates a notification and displays on the window.
We would usually require asking for permission when our web app initially loads. So we will just invoke the requestPermission()inside the constructor.
Now we will make changes in app.component.html page, We will add a button into our app.component.html which will create notifications.
We have added a function notify(), which calls the create()method. The create method on PushNotificationsService takes in two parameters, the title and a set of options.
The following options are supported
Options correspond to the Notification interface of the Notification API: Mozilla developer network.
type the below command over terminal
When app will load first over the browser then it will ask for the permission. Click allow to get the push from the created angular application. Click on show notification button. You should be able to see notifications popping up on the right-bottom or right-top corner of your screen.
You can download complete code from here. Download Code