我是 Firebase 的新手,我一直在尝试制作一个发送/接收通知的 Android 应用程序。这段代码在几周前对我来说工作得很好,但现在它显示错误,尽管我没有做任何更改。
代码:
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.pushNotification = functions.database.ref(`/notification/{user_id}/{notification_id}`).onWrite((change,context) =>{
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification to send',user_id);
const deviceToken = admin.database().ref(`/users/${user_id}/tokenId`);
const senderId = admin.database().ref(`/notification/${user_id}/${notification_id}/fromuser`);
return Promise.all([deviceToken,senderId]).then(results =>{
const tokensSnapshot = results[0];
const sender = results[1];
console.log("Device Token ID: ",tokensSnapshot.val());
console.log("Sender ID: ",sender);
const payload ={
notification: {
title: "New message",
body: "hello",
icon: "ic_launcher_round"
}
};
return admin.messaging().sendToDevice(tokensSnapshot.val(),payload).then(response =>{
response.results.forEach((result,index) =>{
const error = result.error;
if(error){
console.error('Failure sending notification to device',tokensSnapshot.val(),error);
}
else{
console.log('Notification sent to : ',tokensSnapshot.val());
}
});
return null;
});
});
});
错误:
tokensSnapshot.val is not a function
at Promise.all.then.results (/user_code/index.js:24:50)
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
最佳答案
我不希望您的代码能够正常工作。看看你在这里做什么:
const deviceToken = admin.database().ref(`/users/${user_id}/tokenId`);
const senderId = admin.database().ref(`/notification/${user_id}/${notification_id}/fromuser`);
return Promise.all([deviceToken,senderId]).then(results => { ... })
deviceToken
和 senderId
是数据库引用。它们只是指向数据库中的位置。但是,您将它们传递给 Promise.all()
,就好像它们是 promise 一样。它们绝对不是 promise 。这意味着回调中的results
将不包含数据快照对象。
您需要查询数据库中的值并获取这些查询的 promise 。注意使用 once()
来查询引用:
const deviceToken =
admin.database().ref(`/users/${user_id}/tokenId`).once('value');
const senderId =
admin.database().ref(`/notification/${user_id}/${notification_id}/fromuser`).once('value');
once()
返回一个 promise ,该 promise 将通过引用位置的数据快照来解决。
在那之后,您的代码中还有更多需要解决的错误。特别是,您永远不会在 sender
上调用 val()
来获取您尝试查询的原始数据。之后您永远不会在任何地方使用发件人值(因此甚至查询它似乎毫无意义)。
关于javascript - Firebase 实时数据库 fcm 消息发送问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51810796/