使用Firebase FCM和角度发送推送通知

时间:2019-07-11 13:24:00

标签: angular firebase notifications push progressive-web-apps

我正在研究连接到Firebase的角度pwa,并且我试图在未打开应用程序时更新Firebase来获取推送通知。 我可以接收FCM令牌,但是无法在Firebase上添加和更新它。因此,我在显示消息时遇到了一些问题。

我已经构建了firebase-messaging-sw.js和messages-service.ts来检索令牌。

messaging-service.ts:
...
export class MessagingService {
messaging = firebase.messaging();
currentMessage = new BehaviorSubject(null);
tokensCollection: AngularFirestoreCollection<any>;
constructor(private firebasedb: AngularFirestore,   private firebaseAuth: AngularFireAuth) {}

    updateToken(token) {
      this.firebaseAuth.authState.pipe(take(1)).subscribe(() => {
        const data = { token }
        this.firebasedb.collection('fcmTokens/').valueChanges(data)
      })
    }

  getPermission() {
    this.messaging.requestPermission()
    .then(() => {
      console.log('Notification permission granted.');
      return this.messaging.getToken()
    })
    .then(token => {
      console.log(token)

      if(token)

      this.updateToken(token)
    })
    .catch((err) => {
      console.log('Unable to get permission to notify.', err);
    });
  }


  receiveMessage() {
    this.messaging.onMessage(payload => {
      console.log('Message received. ', payload);
      this.currentMessage.next(payload);
    });
  }


firebase-messaging-sw.js:
importScripts("https://www.gstatic.com/firebasejs/6.1.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/6.1.0/firebase-messaging.js");

firebase.initializeApp({
  messagingSenderId: "960679172964"
});

const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  var notificationTitle = 'TeamCalendar';
  var notificationOptions = {
      body: 'New event is available',
      icon: 'assets/icons/icon-72x72.png'
  };
  return self.registration.showNotification(notificationTitle,
  notificationOptions);
});

component.ts:
...
    this.msgService.getPermission();
    this.msgService.receiveMessage();
    this.message = this.msgService.currentMessage;
...

如果Firebase更新且应用未在前台运行,我想接收推送通知。

0 个答案:

没有答案