Browser Push notifications in Angular Applications

March 14, 2017
by Rahil Shaikh
  • Browser push notifications Angular 2

Push notifications are a way to make you application more interactive and automatically push well tailored dynamic content to the user. While this has been a feature mobile applications have been using to their advantage for quite a while. Now browsers have moved in to natively support this feature allowing web developers to integrate them with their web applications.

In this tutorial, we will see how we can easily add browser push notifications to our Angular 2 applications.

We will use angular-cli to scaffold our application. Angular CLI is a good tool to start with, as it hides a lot of the complexity that comes with setting up Angular applications. If you are comfortable with managing modules with systems.config.js you can use an application that we built in one of our earlier tutorials as a starting point. I’ve mentioned the link after this para.

Throughout this article, the word Angular refers to Angular 2 or greater unless mentioned otherwise.

DOWNLOAD

Let’s get to work!

First and foremost we need Angular CLI to be installed globally.

npm install -g @angular/cli

Once done! Create a new Angular project by running …

ng new ciphertrick-notify

I have named our app as ciphertrick-notify.

Navigate inside the project directory and run …

ng serve

This starts up the server, by dfault on http://localhost:4200.

Angular 2 app

Angular 2 app

If you see this, you are good!

Now we are all set to add push notifications.

We will use angular2-notifications module to implement web push notifications in our Angular applications.

Installing the module

It’s simple, as we all know.

npm install --save angular2-notifications
Setting up module loaders

People using Angular CLI need not do anything. For those using systems.config.js see the below snippet.

Add this to your systems.config.js

var map = {
    'angular2-notifications': 'node_modules/angular2-notifications'
}

var packages = {
    'angular2-notifications': { main: 'components.js', defaultExtension: 'js' }
}

 

Importing the module

Open up app.module.ts. We need to import the module and add it to the imports of our AppModule

/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { PushNotificationsModule } from 'angular2-notifications'; //import the module

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    PushNotificationsModule //add it to the imports
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

Adding it to our AppComponent

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.

We will add a button into our app.component.html which will create notifications.
Here is how our component looks.

/src/app/app.component.ts
import { Component } from '@angular/core';
import { PushNotificationsService } from 'angular2-notifications'; //import the service

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Web push Notifications!';

  constructor(private _pushNotifications: PushNotificationsService){
    _pushNotifications.requestPermission(); // request for permission as soon as component loads
  }

  notify(){ //our function to be called on click
    let options = { //set options
      body: "The truth is, I'am Iron Man!",
      icon: "assets/images/ironman.png" //adding an icon
    }
    let notify = this._pushNotifications.create('Iron Man', options).subscribe( //creates a notification
        res => console.log(res),
        err => console.log(err)
    );
  }
}
/src/app/app.component.html
<h1>
  {{title}}
</h1>
<button (click)="notify()">Show Notiication</button>

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
{
body: string
icon: string
tag: string
renotify: boolean
silent: boolean
sound: string
noscreen: boolean
sticky: boolean
dir: 'auto' | 'ltr' | 'rtl'
lang: string
vibrate: number[]
}

Options correspond to the Notification interface of the Notification API: Mozilla developer network.

I have also added an icon to the path /src/assets/images/ironman.png. This icon would be displayed on our notification.

Run The App

Now that we are done, let run the app and test it out.

ng serve

When the application loads you should see something like below.

Angular push notifications

Angular push notifications

Click on Allow, to allow the application to display notifications.

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.

Angular push notifications

Angular push notifications

Conclusion

That was it from this tutorial. Hope now it’s easy for you to show browser push notifications in any Angular 2 application.

Further Links

  1. Angular 2 Notifications Module
  2. Learn Angular 2 From our Free Video Course on YouTube
  3. Learn Angular 2 by building 12 apps

About

Engineer. Blogger. Thinker. Loves programming and working with emerging tech. We can also talk on Football, Gaming, World Politics, Monetary Systems.

Free PDF

Subscribe and get AngularJS Tips PDF. We never spam!
First Name:
Email:

7 comments

  1. |

    Thanks for sharing, it will be fun to try. It can be interesting for user experience depending on the project.

    • Rahil Shaikh
      |

      Indeed it is quite useful.

  2. vasudev
    |

    it is not working in chrome browser in android mobile

  3. |

    Hi,

    If we want to work on a server?. After publishing, nothing works.

    Regards
    Ali

  4. |

    Could you please update on how to use this for newer angular 2 version, i tried the above but not working…

    • |

      This should work with the latest version of Angular.

  5. |

    thank you
    how to use it with api
    when new item added then push the notification i dont know how dow this

Leave a Comment