Browser Push notifications in Angular Applications

April 13, 2019
by Rahil Shaikh
  • Browser push notifications Angular 2

Push notifications are a way to make your 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 see how to add browser push notifications in Angular applications.

To quickly get up and running we will use angular-cli as our development tool. Angular CLI is the official CLI tool used for developing Angular applications. It is also the recommended way for scaffold Angular applications.

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

This article has been updated to support the latest version of Angular.

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 angular-push

I have named our app as angular-push.

Navigate inside the project directory and run …

ng serve

This starts up the server, by default 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 ng-push module to implement web push notifications in our Angular applications. ng-push provides wrappers around the Browser’s notification API.

Installing the module
npm install --save ng-push

 

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 { PushNotificationsModule } from 'ng-push'; //import the module

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

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    PushNotificationsModule // add it to 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.

As our app loads for the first time, we will ask for the user’s consent to show push notifications. To do so we will just invoke the requestPermission() method 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 'ng-push';

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

  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
    }
     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[]
}

You can read more about options in the Notifiations 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 the 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’s a warp for this tutorial. I have tried to keep things as simple and clean as possible. Hope this helped you to integrate browser push notifications in your Angular application.

Further Links

  1. How to add in-app toaster notifications in Angular?
  2. How to add Pagination in Angular Application
  3. How to transfer data between parent and child component in Angular

About

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

Get notified on our new articles

Subscribe to get the latest on Node.js, Angular, Blockchain and more. We never spam!
First Name:
Email:

13 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. |

    Hi,

    import { PushNotificationsService } from ‘angular2-notifications’; doesn’t work 🙁 there is not such a service

  6. |

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

  7. |

    node_modules/angular2-notifications/angular2-notifications”‘ has no exported member ‘PushNotificationsModule’

    I am getting above error message in cmd console

  8. |

    import { PushNotificationsService } from ‘angular2-notifications’; doesn’t work

Leave a Comment