使用FCM进行角度推送通知

时间:2020-06-25 22:04:37

标签: angular firebase push-notification firebase-cloud-messaging service-worker

我需要使用FCM在我的项目中实现推送通知。我已经实现了后端,并且按预期工作。在Angular方面,我能够实现这两种功能(背景和前景),这时我唯一的问题是从推送通知中获取的有效负载没有显示在html文件中。

这是我用来用Angular(https://dev.to/mayurkadampro/angular-8-firebase-cloud-messaging-push-notifications-97a)实现FCM的文章。

这是我的消息传递服务文件:

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);
    });
  }
}

app.component.ts文件

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;
  }

}

最后是firebase-messaging-sw.js文件:

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();

项目中安装的Firebase版本与Service Worker中使用的版本相同。 (7.6.0)

1 个答案:

答案 0 :(得分:1)

我遇到了类似的问题,并通过在Ang上使用ng serve -ssl true标志修复了问题 您必须使用https才能显示前台通知