Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to subscribe background messages via firebase in angular service (Typescript file)

import { Injectable } from "@angular/core";
import { AngularFireMessaging } from "@angular/fire/messaging";
import { BehaviorSubject, Subject } from "rxjs";
@Injectable()
export class AppService {
    currentMessage = new BehaviorSubject(null);
    fcm_key = new BehaviorSubject(null);

    private componentMethodCallSource = new Subject<any>();

    componentMethodCalled$ = this.componentMethodCallSource.asObservable();
    constructor(private angularFireMessaging: AngularFireMessaging) { }

    requestPermission() {
        this.angularFireMessaging.requestToken.subscribe(
            (token: any) => {
                this.fcm_key.next(token);
            },
            (err: any) => {
                console.error("Unable to get permission to notify.", err);
            }
        );
    }

    receiveMessage() {

        this.angularFireMessaging.messages.subscribe((payload: any) => {
            this.componentMethodCallSource.next(payload);
            this.currentMessage.next(payload);
        });
    }
}

In my application, I have subscribed to Firebase (Cloud base) for getting notification messages for both active as well as passive tab. In that, I'm triggering the firebase through PHP CURL (with the firebase key) to get notifications. I'm able to get the notifications using the below functions

Active tabs:

this.angularFireMessaging.messages.subscribe((payload: any) => {
        this.componentMethodCallSource.next(payload);
        this.currentMessage.next(payload);
    });

But I don't have any idea on how to use the below function in angular for getting notification messages even while my app tabs are not active.

this.angularFireMessaging.onBackgroundMessage
like image 469
Eswaramoorthy Karthikeyan Avatar asked Dec 13 '25 21:12

Eswaramoorthy Karthikeyan


1 Answers

I stuggled with this too, so I write this down hoping it could help someone else. My sources comes from here

// firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/9.18.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.18.0/firebase-messaging-compat.js');

firebase.initializeApp({
  ...
});

const messaging = firebase.messaging();

const broadcastChannel = new BroadcastChannel('my-channel');
messaging.onBackgroundMessage((payload) => {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  broadcastChannel.postMessage(payload.data);
});
// in any ts file, for exemple firebase.service.ts
private readonly firebaseMessaging = inject(AngularFireMessaging);

// channel name must be identical as the one in firebase-messaging-sw.js
private readonly backgroundMessages$ = 
  fromEvent(new BroadcastChannel('my-channel'), 'message').pipe(
     map((event: MessageEvent<PushData>) => event.data)
  );
private readonly foregroundMessages$ = this.firebaseMessaging.messages.pipe(
  map((message: firebase.messaging.MessagePayload) => message.data as unknown as PushData)
);
/** combine foreground and background messages from FCM, just subscribe to it :) */
readonly pushMessages$ = of(this.backgroundMessages$, this.foregroundMessages$).pipe(mergeAll(2));

There is also an alternative for getting background messages with a subject

const backgroundMessages$ = new Subject<any>();
new BroadcastChannel('my-channel').onmessage = (event) => backgroundMessages$.next(event.data);
like image 57
TCH Avatar answered Dec 16 '25 14:12

TCH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!