Angular 8 + Firebase Cloud Messaging Push Notifications
Tags: angular, javascript
Published: 2020-01-25 15:04:22

Are you looking for push notification which is normally you seen in ANDROID application or IOS application which is basically giving popup on your device notification tab when the application is closed user still received the notification. The same things can happen with your web application. In the case of the web application, you will receive the notification when the browser tab is not active and this is done by with the help of a service worker.

Now you might be wondering what is service worker ? or what is push notification ? as well so before i begin to explain it’s procedure it's better to understand some terminologies.

<h1>First, take look into what is Push Notifications</h1>

A push notification is a message popup similar to SMS. App publishers can send them at any time; users don’t have to be in the app or using their devices to receive them. They can do a lot of things; for example, they can show the latest sports scores, get a user to take any action, such as downloading a coupon or let a user know about an event, such as a flash sale.

Push notifications look like SMS text messages and mobile alerts, but they only reach users who have installed your app. Each mobile platform and browsers have support for push notifications. It gives applications the ability to receive messages pushed to them from a server, whether or not the web app is in the foreground, or even currently loaded, on a user agent.

<h1>Second, look for prerequisites of Push Notifications</h1>

as we looking push notifications in angular 8 so you must have installed Node.js version > 10. NPM will be updated also because it will be used by default. Here, I am using Node version 10.16.3 and install the latest version of Angular CLI else you can upgrade your older version into the latest CLI by command.
```npm install -g @angular/cli@latest``` 


once the project environment has been done you also require a firebase account to connect your web application into the cloud messaging.

1 ) simply visit into firebase.google.com

2 ) if you are new then click on sign up else you can log in into your old account

3) once login click into go to console tab which is in the top right corner
4) then click into Create a project

5) once the project has been created then look for its project settings General tab and create one app for getting its credentials

6 ) once your app is ready then simply copy its config for future use

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/scuo52wjmcgw8ns1iwv9.png)

7) also copy the server key from the Cloud Messaging tab

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/g6fpcojawwp8670r1rzw.png)

Now your all prerequisites are complete 🙂

<h1>Now Create the Angular Project</h1>

Let’s create an Angular 8 project by using the following command:

```ng new push-notification
   cd push-notification```

here we are using the firebase so we need to install that library so enter the following command in the same project directory.

```npm install firebase @angular/fire --save
   npm install firebase --save
   npm audit fix (if any vulnerabilities found else ignore)```

<h2>Now you have to create some file so follow the instruction carefully.</h2>

1) create manifest.json file save this file in the same folder where index.html file resides. We need to add a manifest.json file to our app and register it with the Angular CLI. Push Notifications use the service worker browser extension, which must be registered in this manifest.

```{
  "gcm_sender_id": "YOUR-SENDER-ID"
}```

then link it in the index.html file.

```<link rel="manifest" href="./manifest.json">```

2. create firebase-messaging-sw.js Push messaging requires a service worker. This allows your app to detect new messages, even after the app has been closed by the user. and create this file in the same directory of manifest.json file which is in src/ directory.
Note:- Before importing the below script you need to check the latest version it's better if you import the latest version of the CDN link, so here i importing 7.6.0 version links.

```
importScripts('https://www.gstatic.com/firebasejs/7.6.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.6.0/firebase-messaging.js');
  firebase.initializeApp({
   apiKey: “from firebase config”,
   authDomain: “from firebase config”,
   databaseURL: “from firebase config”,
   projectId: “from firebase config”,
   storageBucket: “from firebase config”,
   messagingSenderId: “from firebase config”,
   appId: “from firebase config”,
   measurementId: “from firebase config”
});
  const messaging = firebase.messaging();
```

3. we need to register these files in angular-cli.json

```
"assets": [
    "src/favicon.ico",
    "src/assets",
    "src/firebase-messaging-sw.js", // add this one
    "src/manifest.json" // this one also 
]
```

4. Now you have to create the service provider in my case I'm going to create a messaging service provider in the service folder which is an app directory. so move into the app directory and enter bellow command by cmd.

```
mkdir service
cd service
ng g s messaging
```

once service has been created you have to paste below exact code into messaging.service.ts file

```
import { Injectable } from '@angular/core';
import { AngularFireMessaging } from '@angular/fire/messaging';
import { BehaviorSubject } from 'rxjs'
@Injectable()
export class MessagingService {
currentMessage = new BehaviorSubject(null);
constructor(private angularFireMessaging: AngularFireMessaging) {
this.angularFireMessaging.messaging.subscribe(
(_messaging) => {
_messaging.onMessage = _messaging.onMessage.bind(_messaging);
_messaging.onTokenRefresh = _messaging.onTokenRefresh.bind(_messaging);
}
)
}
requestPermission() {
this.angularFireMessaging.requestToken.subscribe(
(token) => {
console.log(token);
},
(err) => {
console.error('Unable to get permission to notify.', err);
}
);
}
receiveMessage() {
this.angularFireMessaging.messages.subscribe(
(payload) => {
console.log("new message received. ", payload);
this.currentMessage.next(payload);
})
}
}
```

let’s understand its functions

requestPermission(): Browser/ device will ask to user for permission to receive notification. After permission is granted by the user, firebase will return a token that can use as a reference to send a notification to the browser.

receiveMessage(): This function will be triggered when a new message has received.

6. Update the Environment files

```
export const environment = {
production: false,
firebase: {
  apiKey: “from firebase config”,
  authDomain: “from firebase config”,
  databaseURL: “from firebase config”,
  projectId: “from firebase config”,
  storageBucket: “from firebase config”,
  messagingSenderId: “from firebase config”,
  appId: “from firebase config”,
  measurementId: “from firebase config”
}
};
```

7. Update the Components files

first, we will update the App Module File

```
import { BrowserModule } from ‘@angular/platform-browser’;
import { NgModule } from ‘@angular/core’;
import { AppRoutingModule } from ‘./app-routing.module’;
import { AppComponent } from ‘./app.component’;
import { AngularFireMessagingModule } from ‘@angular/fire/messaging’;
import { AngularFireDatabaseModule } from ‘@angular/fire/database’;
import { AngularFireAuthModule } from ‘@angular/fire/auth’;
import { AngularFireModule } from ‘@angular/fire’;
import { MessagingService } from ‘./service/messaging.service’;
import { environment } from ‘../environments/environment’;
import { AsyncPipe } from ‘../../node_modules/@angular/common’;
@NgModule({
   declarations: [AppComponent],
   imports: [
      AppRoutingModule,
      BrowserModule,
      AngularFireDatabaseModule,
      AngularFireAuthModule,
      AngularFireMessagingModule,
      AngularFireModule.initializeApp(environment.firebase),
   ],
   providers: [MessagingService,AsyncPipe],
   bootstrap: [AppComponent]
})
export class AppModule { }
```

then in the HTML part, we can use pipe async and JSON

```
{{ message | async | json }}
```

And now update the App Components file

```
import { Component } from ‘@angular/core’;
import { MessagingService } from ‘./service/messaging.service’;
@Component({
  selector: ‘app-root’,
  templateUrl: ‘./app.component.html’,
  styleUrls: [‘./app.component.css’]
})
export class AppComponent {
  title = ‘push-notification’;
  message;
  constructor(private messagingService: MessagingService) { }
ngOnInit() {
  this.messagingService.requestPermission()
  this.messagingService.receiveMessage()
  this.message = this.messagingService.currentMessage
 }
}
```

Finally, we did the Setup process... 😉

Now run the project
run application using ng serve -o after compilation is complete, open can your browser and browser will ask for permission.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/sjnlc2g6lamh1g7cor28.png)

once you click on the allow button than it will print the token id on browser console sometime it will take time to load the token id but surely you will get that id in console dialog.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/8ichgziuosof5ubr0iwr.png)

now we are ready to go…

<h1>Now look for sending a push notification</h1>

You can also hit Firebase Cloud Messaging directly using cURL.

```
curl -X POST \
  https://fcm.googleapis.com/fcm/send \
  -H 'Authorization: key=YOUR-SERVER-KEY' \
  -H 'Content-Type: application/json' \
  -d '{ 
 "notification": {
  "title": "Hey there", 
  "body": "Subscribe to mighty ghost hack youtube channel"
 },
 "to" : "YOUR-GENERATED-TOKEN"
}'
```

Also, you can use the postman for sending the request i will demonstrate you by the postman

copy below JSON request and enter into the body part and also provide authorization key in the header section of postman before sending any request over googleapis and authorization key is nothing but the legacy serve key which we saw in prerequisite sections.

```
{
 "notification": {
 "title": "Hey there", 
 "body": "Subscribe to might ghost hack youtube channel"
 },
 "to" : "YOUR-GENERATED-TOKEN"
}
```

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/ytzu864vty5r69dxnusz.png)

once all done we can send the request to the server https://fcm.googleapis.com/fcm/send 

once i click on the send button on postman i will receive the popup and one thing important you have to note down when your project is in active tab means open in browser or you are in the same tab then message will appear on HTML but it will not give you any popup until and unless you minimize it or move into another tab. when you move into another tab or minimize the browser than service worker doing his work to show you the popup message

now let me show the popup when the project tab is not in an active mode

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/xzqhvgukstfyglr8lteb.png)

now look in active mode

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/1n43fuwd9j7xpti7h664.png)

<h1>Video Tutorial</h1>

{% youtube ODE9l1c3ujY %}

That’s it 😃

hope you get it how easily we can configure the angular project to receive the push notification.

If you want to look into the project than here is the GitHub link:- mayurkadampro/Angular-Push-Notification