4

I need to implement push notifications in my project using FCM. I already implement the backend side and is working as expected. In the Angular side, I was able to implement both functionalities (background and foreground), my only problem at this point is that the payload that I get from the push notification is not being displayed in my html file.

This is the article that I used to implement the FCM with Angular (https://dev.to/mayurkadampro/angular-8-firebase-cloud-messaging-push-notifications-97a).

This is my messaging servile file:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { AngularFireMessaging } from '@angular/fire/messaging';

@Injectable({
  providedIn: 'root'
})

export class MessagingService {
  currentMessage = new BehaviorSubject(null);
 
  constructor(private angularFireMessaging: AngularFireMessaging) {
  }
 
  requestPermission() {
    this.angularFireMessaging.requestToken.subscribe((token) => {
      console.log('Permission granted! Save to the server!', token);
    }, (error) => {
      console.log(error);
    })
  }
 
  receiveMessage() {
    this.angularFireMessaging.onMessage((payload) => {
      console.log('Message received. ', payload);
      this.currentMessage.next(payload);
    });
  }
}

The app.component.ts file

import { Component, OnInit } from '@angular/core';
import { MessagingService } from './services/messaging.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent implements OnInit {
  title = 'pn';
  message;

  constructor(private _messagingSrv: MessagingService ) {}

  ngOnInit() {
    this._messagingSrv.requestPermission();
    this._messagingSrv.receiveMessage();
    this.message = this._messagingSrv.currentMessage;
  }

}

and finally, the firebase-messaging-sw.js file:

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: "XXXXXXXXXXXXXXXXX",
  authDomain: "XXXXXXXXXXXXXXXXX",
  databaseURL: "XXXXXXXXXXXXXXXXX",
  projectId: "XXXXXXXXXXXXXXXXX",
  storageBucket: "XXXXXXXXXXXXXXXXX",
  messagingSenderId: "XXXXXXXXXXXXXXXXX",
  appId: "XXXXXXXXXXXXXXXXX",
  measurementId: "XXXXXXXXXXXXXXXXX"
});

const messaging = firebase.messaging();

The firebase version installed in the project is the same one used in the service worker. (7.6.0)

Jose R. Chacón
  • 99
  • 1
  • 12

1 Answers1

2

I had a similar problem and fixed by using ng serve -ssl true flag on angular you gotta be on https in order to show foreground notifications

Daggle
  • 171
  • 1
  • 1
  • 10