Implement FireBase Notification In Angular Version 14.1.0

Installation

  • npm i @angular/fire (Version : ^7.6.1) 

  • npm i firebase (Version: ^10.5.0)

Setup Firebase Configuration

  • Create one file for firebase configuration in src/app folder (firebase-config.ts)

  • Past your firebase config in firebase-config.ts

export const firebaseConfig = {

  apiKey: YOUR APIKEY,

  authDomain: YOUR AUTHDOMAIN,

  projectId: YOUR PROJECTID,

  storageBucket: YOUR STORAGEBUCKET,

  messagingSenderId: YOUR MESSAGINGSENDERID,

  appId: 'YOUR APPID,

  vapidKey: 'YOUR VAPIDKEY,

};

Initialize Firebase And Setup Notifications Code

  • Write this code in your app.module.ts file.

import { firebaseConfig } from './firebase-config';

import { initializeApp } from "firebase/app";

initializeApp(firebaseConfig);

  • Import AngularFireDatabaseModule in app.module.ts

  • Add this code in provider app.module.ts 

providers: [

  { provide: FIREBASE_OPTIONS, useValue: firebaseConfig },

]

  • Create firebase-messaging-sw.js in src/ and past this code

importScripts("https://www.gstatic.com/firebasejs/9.1.3/firebase-app-compat.js");

importScripts("https://www.gstatic.com/firebasejs/9.1.3/firebase-messaging-compat.js");

firebase.initializeApp({

 apiKey: "***************",

 authDomain: "***************",

 projectId: "***************",

 storageBucket: "***************",

 messagingSenderId: "***************",

 appId: "***************",

 measurementId: "***************"

});

const messaging = firebase.messaging();

  • Create manifest.json in src/ and past this code

{

  "gcm_sender_id": "***************"

}

  • Open the angular.json file and paste this code in the assets section

"assets": [

              "src/firebase-messaging-sw.js",

              "src/manifest.json"

            ],



  • Create CLIENT_FCM_TOKEN 

import { getToken, getMessaging } from 'firebase/messaging';
import * as firebase from 'firebase/messaging';

 requestPermission() {

  if (!await firebase.isSupported()) {

      alert("Oops! Your browser doesn't support notifications");

      return;

   }

  const messaging = getMessaging();

  const token = await getToken(messaging, {    

vapidKey:firebaseConfig.vapidKey 

    });

  localStorage.setItem('fcm_token', token);

  return token;

}


  • Create a listening method for real-time get notifications
    import { getToken, getMessaging } from 'firebase/messaging';

messagesData = [];

  listen() {

    const messaging = getMessaging();

    onMessage(messaging, (data) => {

        if (data) {

          this.messagesData.push(data);

        }

    });

  }



Post a Comment

Previous Post Next Post