Я хочу добавить Firebase Pu sh Уведомления, но есть несколько проблем. Я следую этим руководствам: https://medium.com/@a.adendrata / pu sh -notifications-with- angular -6-firebase-cloud-massaging-dbfb5fbc0eeb https://medium.com/mighty-ghost-hack/angular-8-firebase-cloud-messaging-push-notifications-cc80d9b36f82
1. Я не уверен, где использовать этот идентификатор. В firebasoConfig это называется messagingSenderId. введите описание изображения здесь
2. Другой идентификатор переходит к manifest.webmanifest. Правильно ли следующее утверждение?
gcm_sender_id одинаково для ВСЕХ приложений в мире, не меняйте его.
{
"gcm_sender_id": "103953800507"
}
3. У меня консольная ошибка о разрешениях firebase.
index.esm. js: 106 [2020-07-12T17: 48: 16.265Z] @ firebase / database: FIREBASE WARNING: обновление в / fcmTokens не удалось: разрешено_зона-вечнозеленый. js: 659 Отклонение необработанного обещания: PERMISSION_DENIED: разрешение отклонено; Зона:; Задача: WebSocket.addEventListener: message; Значение: Ошибка: PERMISSION_DENIED: Permission denied
до того, как эта ошибка перейдет в console.log из PushNotificationService с токеном. Полагаю, я неправильно применил userId. Какой идентификатор мне отправить?
КОД:
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({
......
credentials
...
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken().then((currentToken) => {
if (currentToken) {
console.log(currentToken)
sendTokenToServer(currentToken);
updateUIForPushEnabled(currentToken);
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
// Show permission UI.
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
showToken('Error retrieving Instance ID token. ', err);
setTokenSentToServer(false);
});
Здесь снова выводится сообщение об ошибке из console.log («Произошла ошибка при получении токена.», Ошибка)
Произошла ошибка при получении токена. ReferenceError: sendTokenToServer не определен в firebase-messaging-sw. js: 25 firebase-messaging-sw. js: 36 Uncaught (в обещании) ReferenceError: showToken не определен
manifest.webmanifest
{
"name": "app",
"short_name": "app",
"theme_color": "#1976d2",
"background_color": "#fafafa",
"display": "standalone",
"scope": "./",
"start_url": "./",
"gcm_sender_id": "103953800507",
"icons": [
{
"src": "assets/icons/icon-72x72.png",
"sizes": "72x72",
"type": "image/png",
"purpose": "maskable any"
},
}....
AppComponent
constructor(private push: PushNotificationService)
{}
ngOnInit() {
this.initNotify()
}
initNotify() {
const userId = '001'
this.push.requestPermission(userId)
this.push.receiveMessage()
this.message = this.push.currentMessage
}
PushNotificationService
import { Injectable } from '@angular/core'
import { AngularFireDatabase } from '@angular/fire/database'
import { AngularFireAuth } from '@angular/fire/auth'
import { AngularFireMessaging } from '@angular/fire/messaging'
import { take } from 'rxjs/operators'
import { BehaviorSubject } from 'rxjs'
@Injectable({
providedIn: 'root'
})
export class PushNotificationService {
currentMessage = new BehaviorSubject(null);
constructor(
private angularFireDB: AngularFireDatabase,
private angularFireAuth: AngularFireAuth,
private angularFireMessaging: AngularFireMessaging) {
this.angularFireMessaging.messages.subscribe(
(_messaging: any) => {
_messaging.onMessage = _messaging.onMessage.bind(_messaging);
_messaging.onTokenRefresh = _messaging.onTokenRefresh.bind(_messaging);
}
)
}
/**
* update token in firebase database
*
* @param userId userId as a key
* @param token token as a value
*/
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)
})
}
/**
* request permission for notification from firebase cloud messaging
*
* @param userId userId
*/
requestPermission(userId) {
this.angularFireMessaging.requestToken.subscribe(
(token) => {
console.log(token);
this.updateToken(userId, token);
},
(err) => {
console.error('Unable to get permission to notify.', err);
}
);
}
/**
* hook method when new notification received in foreground
*/
receiveMessage() {
this.angularFireMessaging.messages.subscribe(
(payload) => {
console.log("new message received. ", payload);
this.currentMessage.next(payload);
})
}
}