如何将推送通知从Angle 6项目发送到Android应用

时间:2018-08-30 19:55:43

标签: javascript node.js angular firebase push-notification

我有一个Android应用,其中我使用带有nodejs的firebase admin sdk发送推送通知。

运行脚本时,我能够从nodejs原始脚本发送通知。

enter image description here

但是,我只是构建了一个管理仪表板,用于将通知发送到使用angular 6的应用程序,但不知道如何将nodejs脚本与新的angular应用程序集成在一起,以便我只需单击即可从angular应用程序发送通知

我还鼓励就如何最好地做到这一点提出新的想法。 附件是来自nodejs管理脚本的屏幕截图

2 个答案:

答案 0 :(得分:1)

例如,使用Express将节点设置为充当API服务器。

将脚本包装为Express模块​​(名为send-message.js),基本上只是将其导出即可:

const sendMessage = (...params) => {
   //your send message logic, I would do copy paste of your code here however it is an image
}

module.exports = sendMessage;

然后设置调用该脚本的API路由:

var express = require('express')
var sendMessage = require('./send-message')
var app = express()

app.get('/send-message', function (req, res) {
  sendMessage(....);
  res.status(200).end();
})

app.listen(3000)

最后在Angular中使用HttpClient来调用API。

答案 1 :(得分:1)

我终于使用firebase cloud functions解决了这个问题。

  1. 首先,我使用此guide
  2. 在firebase上设置云功能
  3. 然后,我创建了一个名为sendNotification()的云函数,每次将新对象插入Firebase实时数据库时都会触发该函数。
  4. 然后我将现有的通知代码放入sendNotification()函数中
  5. 将该功能部署到我的Firebase控制台
  6. 然后,在一些数据库触发器触发后,通知已发送到我的设备

`

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp();


//This functions listens to the node '/Food menu/date/Food' for new insert and sends notification to a client
exports.sendNotification = functions.database.ref('/Food menu/date/Food')
.onCreate((snapshot, context) => {

  //place your client app registration token here, this is created when a user first opens the app and it is stored in the db. 
  //You could also retrieve the token from the db but in this case it is hard coded
  var registrationToken = "{my-registration-token}";

  //This is the payload for notification

  var payload = {
    data: {
      'title': 'Tomorrow\'s Menu',
      'message': 'Hello, kindly check the menu available for today',
      'is_background': 'true',
      'image': 'http://www.allwhitebackground.com/images/3/3430.jpg',
      'timestamp': '234'
    }
  };

  // Send a message to the device corresponding to the provided
  // registration token.
  admin.messaging().sendToDevice(registrationToken, payload)
    .then((response) => {
      // Response is a message ID string.
      console.log('Successfully sent message:', response);

      //return a promise here since this function is asynchronous
      return "Yes";
    })
    .catch((error) => {
      console.log('Error sending message:', error);
    });

  //return snapshot.ref.parent.child('uppercaseFood').set(uppercase);
});

`

此后,您运行firebase deploy --only functions来部署云功能

阅读此guide,了解有关云功能的更多信息