Angular 11 + Firebase Cloud Messaging Push Notifications — Devstringx

What are Push Notifications:-

Steps to Set Up the Firebase Account –

Create the Angular Project

ng new push-notification
cd push-notification
npm install firebase @angular/fire --save
npm install firebase --save
npm audit fix (if any vulnerabilities are found else ignore them)
  1. Create a JSON file. save this file in the same folder where the index.html file is present. We need to add a manifest.json file to our angular app and register it with the Angular CLI.
{
"gcm_sender_id": "YOUR-SENDER-ID"
}
<head>
<link rel="manifest" href="./manifest.json">
</head>
  1. Create firebase-messaging-sw.js Push messaging requires a service worker. This allows your angular app to detect new messages, even after the angular app has been closed by the user and it is needed to create this file in the same directory as the manifest.json file which is in the src/ directory.
importScripts('https://www.gstatic.com/firebasejs/8.0.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.0.2/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();
"assets": [
"src/favicon.ico",
"src/assets",
"src/firebase-messaging-sw.js", // add this one
"src/manifest.json" // this one also
]
  1. Now we have to create the service provider here I’m going to create a messaging service provider in the service folder which is an angular app directory. so move into the app directory and enter the below command in cmd.
mkdir service
cd service
ng g s messaging
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);
})
}
}
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”
}
};
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 { }
{{ message | async | json }}
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
}
}

Run the Project

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"
}'
{
"notification": {
"title": "Hey there",
"body": "Subscribe to might ghost hack youtube channel"
},
"to": "YOUR-GENERATED-TOKEN"
}
Above screenshot include your legacy server key in the header section

--

--

Devstringx Technologies is highly recommended IT company for custom software development, mobile app development and automation testing services

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Devstringx Technologies

Devstringx Technologies is highly recommended IT company for custom software development, mobile app development and automation testing services