我已尝试使用 Firebase 云功能发送通知。我的项目结构
这是 index.js,
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.pushNotification = functions.database.ref('/messages').onWrite( event => {
console.log('Push notification event triggered');
const message = event.data.val();
const user = event.data.val();
console.log(message);
console.log(user);
const topic = "myTopic";
const payload = {
"data": {
"title": "New Message from " + user,
"detail":message,
}
};
return admin.messaging().sendToTopic(topic, payload);
});
以上代码配置错误,我在Node.js中部署时,LOG in Function显示:
"TypeError: Cannot read property 'val' of undefined".
实际上我正在尝试做什么: 我正在尝试从快照加载中提取信息到 index.js 中,这样当一个新的 child 被添加到实时数据库时,它应该触发一个带有标题和正文的通知负载。
在 Android 中,我使用子监听器,用于在添加新记录时进行监听
FirebaseDatabase.getInstance().getReference().child("messages")
OnChildAdded(.....){
if (dataSnapshot != null) {
MessageModel messageModel = dataSnapshot.getValue(MessageModel.class);
if (messageModel != null) {
// do whatever
}
}
但在 index.js 中,我无法解析它。 非常感谢根据我的数据库结构修复 index.js 的一些指导。 PS-我从来没有用JS写过代码 如果您需要更多上下文,我很乐意提供。
最佳答案
改变这个:
exports.pushNotification = functions.database.ref('/messages').onWrite( event => {
const message = event.data.val();
const user = event.data.val();
});
到这里:
exports.pushNotification = functions.database.ref('/messages').onWrite(( change,context) => {
const message = change.after.val();
});
请检查:
https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database
云函数已更改,现在 onWrite
有两个参数 change
和 context
change
有两个属性 before
和 after
,每个属性都是一个 DataSnapshot
列出的方法这里:
https://firebase.google.com/docs/reference/admin/node/admin.database.DataSnapshot
关于javascript - Firebase 类型错误 : Cannot read property 'val' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49746905/