从Firebase云功能发送通知获取为通知的null

时间:2019-07-20 09:52:13

标签: android firebase firebase-realtime-database firebase-cloud-messaging google-cloud-functions

当我从Firebase云功能发送通知时,将子级添加到Firebase数据库时,它成功发送了一条通知,但是当我从Firebase数据库中删除该子级时,我收到通知,因为下面的空消息是我得到的屏幕快照链接我从Firebase数据库删除子项时收到通知

Image

//import firebase functions modules
const functions = require('firebase-functions');

//import admin module
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

// Listens for new debate created
exports.pushNotifications = functions.database.ref('app_title').onWrite(( change,context) => {
    console.log('Push notification event triggered');

       const app_title = change.after.val();

        const payload = {notification: {
            title: 'New Notification',
            body: `${app_title}`
            }
        };

   return admin.messaging().sendToTopic("appGlobal",payload)
       .then(function(response){
            console.log('Notification sent successfully:',response);
       })
       .catch(function(error){
            console.log('Notification sent failed:',error);
       });
});

1 个答案:

答案 0 :(得分:0)

change.after.val()为空,因为它已被删除,您应返回change.before.val()以删除操作(参考answer

检查更改以检测删除

//Comment created

if (change.after.exists() && !change.before.exists()) {
    return //TODO
    });

    //Comment deleted
} else if (!change.after.exists() && change.before.exists()) {
    return //TODO              
    });

    //Comment updated
}  else if (change.after.exists() && event.data.previous.exists()) {
        return //TODO
    }

您需要实现onCreateonDelete而非onWrite以获得更好的结果

  

onWrite(),在以下位置创建,更新或删除数据时触发   实时数据库。

     

onCreate(),在实时创建新数据时触发   数据库。

     

onUpdate(),在实时更新数据时触发   数据库。

     

onDelete(),当从实时删除数据时触发   数据库。 (ref)