首页 > 解决方案 > Angular Firebase 后台推送通知

问题描述

我有一个角度项目,我们在其中使用 firebase 推送通知。当应用程序处于活动状态(查看)时,我能够获取推送通知消息,但在应用程序处于非活动状态(后台)时无法获取推送消息。请帮忙。

这是代码。

firebase-messaging-sw.js

importScripts('https://www.gstatic.com/firebasejs/7.24.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.24.0/firebase-messaging.js');
firebase.initializeApp({
    apiKey: "<API-KEY>",
    authDomain: "<AUTHDOMAIN>",
    databaseURL: "<DATABASEURL>",
    projectId: "<PROJECTID>",
    storageBucket: "<STORAGEBUCKET>",
    messagingSenderId: "<MESSAGINGSENDERID>",
    appId: "<APPID>",
    measurementId: "<MEASUREMENTID>"
});
const messaging = firebase.messaging();
 
// [START messaging_on_background_message]
messaging.onBackgroundMessage((payload) => {

const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle,notificationOptions);
    });

消息服务.ts 文件

export class MessagingService {
  currentMessage = new BehaviorSubject(null);
  public isFcmToken = new Subject<boolean>();
  
  public pushMsgRcvdEvent = new Subject<{ payload: any }>();

  constructor(private angularFireMessaging: AngularFireMessaging) {
    this.angularFireMessaging.messaging.subscribe(
      (_messaging) => {
        _messaging.onMessage = _messaging.onMessage.bind(_messaging);
        _messaging.onBackgroundMessage = _messaging.onBackgroundMessage.bind(_messaging);
      }
    );

  }


    
  requestPermission() {
    // Code hidden
    ...
  }
  
  receiveMessage() {
    this.angularFireMessaging.messages.subscribe(
      (payload) => {
        console.log("new message received. ", payload);
        this.currentMessage.next(payload);
        this.pushMsgRcvdEvent.next({ payload: payload });
      });
  }

}

我的问题是我能够获取推送消息并将其记录为“收到新消息”。在 receiveMessage() 中,但是当用户不活动(后台)时,我的推送消息由 firebase-messaging-sw.js 文件中的 onBackgroundMessage() 处理,但它不会到达 receiveMessage()。

我正在使用角度 8,“@angular/fire”:“^5.2.3”,“firebase”:“^7.24.0”

标签: angularfirebasepush-notificationfirebase-cloud-messaging

解决方案


推荐阅读