Уведомления Pu sh не работают на рабочем сервере - PullRequest
1 голос
/ 16 марта 2020

Мой код работает правильно в локальной среде, но уведомления не работают на производстве. Я использую angular 8 . Используется Firebase 7.6.0.
Когда я отправляю уведомление pu sh с консоли Firebase, оно работает нормально, но когда какой-то запрос поступает с панели администратора живого сервера, уведомления не отправляются. Node.js используется для Backend.

 constructor(private messagingService: MessagingService){
    if ("serviceWorker" in navigator) {
      console.log('--------in service qorker condition')
        window.addEventListener("load", function() {
          navigator.serviceWorker.register("./firebase-messaging-sw.js").then(
            function(registration) {
            console.log(
                "ServiceWorker registration successful with scope: ",
                registration.scope
              );
            },
            function(err) {
              // registration failed :(
              console.log("ServiceWorker registration failed: ", err);
            }
          );
        });
      }

  }

 ngOnInit() {
    // const userId = 'user001';
    // this.messagingService.requestPermission(userId);
    this.messagingService.receiveMessage();
  }

Выше app.component.ts вызов конструктора

import { Injectable } from '@angular/core';
import { AngularFireMessaging } from '@angular/fire/messaging';
import { BehaviorSubject } from 'rxjs'
import { AngularFireDatabase } from '@angular/fire/database';
import { AngularFireAuth } from '@angular/fire/auth';
import { take } from 'rxjs/operators';

@Injectable()
export class MessagingService {
  token: any = "";
currentMessage = new BehaviorSubject(null);
constructor(private angularFireDB: AngularFireDatabase,
  private angularFireAuth: AngularFireAuth,
  private angularFireMessaging: AngularFireMessaging) {
  this.angularFireMessaging.messaging.subscribe(
   (_messaging) => {
    _messaging.onMessage = _messaging.onMessage.bind(_messaging);
    _messaging.onTokenRefresh = _messaging.onTokenRefresh.bind(_messaging);
    }
  )
}

updateToken(userId, token) {
  // we can change this function to request our backend service
  this.angularFireAuth.authState.pipe(take(1)).subscribe(
    () => {
      const data = {};
      data[userId] = token
      this.angularFireDB.object('fcmTokens/').update(data)
    })
}
requestPermission(userId) {
this.angularFireMessaging.requestToken.subscribe(
 (token) => {
  console.log(token);
  this.token = token;
  this.updateToken(userId, token);
 },
 (err) => {
  console.error('Unable to get permission to notify.', err);
 }
 );
}


receiveMessage() {

  this.angularFireMessaging.messages.subscribe((payload: any) => {
    if (payload) {
      console.log(payload, '----lasjkdfl');
      navigator.serviceWorker.ready.then(function(service_worker) {
        service_worker.showNotification(payload.notification.title, {
          body: payload.notification.body
        });
      });
      console.log("new message received. ", payload);
      this.currentMessage.next(payload);
    }
    else{
console.log("no payload recieved");
    }
  });
}
}

Выше службы сообщений

 this.messagingService.requestPermission(userId);
 this.messagingService.receiveMessage();
 this.message = this.messagingService.currentMessage;

Выше код вызывается в login.component.ts

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-messaging-sw. js конфигурации

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...