我一直在寻找一种在Firebase实时数据库发生变化时收到通知的方法。 最后我找到了这个解决方案(下面的链接),但是这个方法适用于Firestore,而不是数据库。 我真的无法更改它以使其在Firebase数据库而不是Firestore上运行。 有人可以帮我这个吗?这对我来说非常重要。 我是打字稿/ firebase的新手。
感谢。
我的数据库:
page index.ts:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp(functions.config().firebase);
exports.newSubscriberNotification = functions.firestore
.document('subscribers/{subscriptionId}')
.onCreate(async event => {
const data = event.data()
const userId = data.userId
const subscriber = data.subscriberId
// Notification content
const payload = {
notification: {
title: 'New Subscriber',
body: `${subscriber} is following your content!`,
icon: 'link to icon'
}
}
// ref to the parent document
const db = admin.firestore()
const devicesRef = db.collection('devices').where('userId', '==', userId)
// get users tokens and send notifications
const devices = await devicesRef.get()
const tokens = []
devices.forEach(result => {
const token = result.data().token;
tokens.push( token )
})
return admin.messaging().sendToDevice(tokens, payload)
});
提供者fcm.ts:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Firebase } from '@ionic-native/firebase';
import { Platform } from 'ionic-angular';
import { AngularFirestore } from 'angularfire2/firestore';
@Injectable()
export class FcmProvider {
constructor(
public firebaseNative: Firebase,
public afs: AngularFirestore,
private platform: Platform
) {
}
async getToken() {
let token;
if (this.platform.is('android')) {
token = await this.firebaseNative.getToken()
}
if (this.platform.is('ios')) {
token = await this.firebaseNative.getToken();
const perm = await this.firebaseNative.grantPermission();
}
// Is not cordova == web PWA
if (!this.platform.is('cordova')) {
// TODO add PWA support with angularfire2
}
return this.saveTokenToFirestore(token)
}
private saveTokenToFirestore(token) {
if (!token) return;
const devicesRef = this.afs.collection('devices');
const docData = {
token,
userId: 'testUser',
}
return devicesRef.doc(token).set(docData)
}
listenToNotifications() {
return this.firebaseNative.onNotificationOpen()
}
}
最后是home.ts页面:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { FcmProvider } from '../../providers/fcm/fcm';
import { ToastController } from 'ionic-angular';
import { Subject } from 'rxjs/Subject';
import { tap } from 'rxjs/operators';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public fcm: FcmProvider, public toastCtrl: ToastController) {}
ionViewDidLoad(){
// Get a FCM token
this.fcm.getToken()
this.fcm.listenToNotifications().pipe(
tap(msg => {
const toast = this.toastCtrl.create({
message: msg.body,
duration: 3000
});
toast.present();
})
)
.subscribe()
}
}
ps:此解决方案与Firestore完美配合。