Angular 9 + Firebase Push Notification

Published by Gajanan Shinde on

Push Notification

Firstly you have to create some files so follow the instructions carefully.

1. Create manifest.json in src folder same where index.html is located and now connect this manifest.json to our Firebase app as

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

The question arise as where to find your sender id go to firebase project and go to Project settings/cloud messaging you will find your sender id

then link it in the index.html file.

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

2.Now create firebase-messaging-sw.js which is a service worker file which helps us to make notify us even app is closed.create this file in same folder where manifest.json is in i.e src folder. Before importing please update the latest version of the CDN link

importScripts('https://www.gstatic.com/firebasejs/7.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.8.1/firebase-messaging.js');
firebase.initializeApp({
    apiKey: "AIXXXXXXXXXXXXXXXXYYYYYYYYYYYjZcPI",
    authDomain: "XXXXX-YYYYY.firebaseapp.com",
    databaseURL: "https://XXXXX-YYYYY.firebaseio.com",
    projectId: "XXXXX-YYYYY",
  	storageBucket: "XXXXX-YYYYY.appspot.com",
    messagingSenderId: "98765432101",
    appId: "1:98765432101:web:fXXXXXXXXYYYYYYY2",
    measurementId: "G-ABCDEFGHI"
    
  });

const messaging = firebase.messaging();

3. We need to register these files in angular.json

"assets": [
			"src/assets", 
			"src/favicon.ico",
			"src/favicon.png",
			"src/firebase-messaging-sw.js",    <--  ADD THIS
			"src/manifest.json" 				<-- ADD THIS
	]

4. Now we have to create the service provider .We need to create a messaging service provider in the service folder which is an app directory. So, move into the app directory and enter below command by cmd.

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(
     (msgings) => {
   msgings.onMessage = msgings.onMessage.bind(msgings);
   msgings.onTokenRefresh=msgings.onTokenRefresh.bind(msgings);
    })
  }
 
  requestPermission() {
    this.angularFireMessaging.requestToken.subscribe(
    (token) => {
    console.log(token);
    });
  }
 
  receiveMessage() {
    this.angularFireMessaging.messages.subscribe(
    (msg) => {
    console.log("show message!", msg);
    this.currentMessage.next(msg);
       })
    }
}

5.Put MessageService in app.module.ts provider

  providers: [MessagingService]

6.How its functions works: 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 been received.

7.Also import AngularFireMessagingModule

import { MessagingService } from './messaging.service';
import{AngularFireMessagingModule}from'@angular/fire/messaging';
import { AsyncPipe } from '@angular/common';

@NgModule({
  imports: [
    AngularFireMessagingModule      <-- //Add this
  ],
  providers: [MessagingService,AsyncPipe]
})

8.Then in HTML template we use Async pipe and JSON pipe. In app.component.html

{{ show | async | json }}

9.Call messaging service in app.component.ts

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

We have completed the coding part!!

10.Now Run the Project by

ng serve -o

After completion of compilation, suddenly browser ask you for permission

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.

11.Now see how to send push notification 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 Gajanan", 
 "body": "Thanks for visiting omnidecoder.com"
 },
 "to" : "YOUR-GENERATED-TOKEN"
}

Copy paste it in postman body>switch none to row and then select next tab as JSON as below

Include your server key in the header section select KEY as Authorization and VALUE as key=server key ,as shown below

Where to find server key? Here!!

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

Hurray!!!! you have Successfully activate push up notification If you want to look into the project than here is the GitHub link:- https://github.com/iamgajanan/Angular-9-Firebase-Push-Notification


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *