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();
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
]
And you can do reference below code for service code.
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.
firebase-messaging-sw.jsfile in angular.json? - Lovely