如何在使用FCM的AngularJS Web应用程序中接收推送通知?

9

当服务器通过 FCM 发送消息时,我希望在 Angular web 应用程序上显示推送通知。最好的方法是什么?是否有适用于此的 Angular 插件(我必须承认我自己找不到)。


可能是在MVC Web应用程序上实现FCM(Firebase Cloud Messaging)的重复问题。 - gmuraleekrishna
2个回答

0

按照 Firebase Javascript Web Setup 的步骤,您只需要暴露对象并在适当的 Angular 组件中执行初始化即可。

更新于 2019 年 1 月 28 日请确保添加脚本标签以获取 firebase-messaging bundle <script src="https://www.gstatic.com/firebasejs/4.9.0/firebase-messaging.js"></script>,但如果您使用 browserify 等工具,则可以完全遵循他们的文章和示例。

以下是原始 JavaScript 代码:

<script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>

<script>
  // Initialize Firebase
  // TODO: Replace with your project's customized code snippet
  var config = {
    apiKey: "<API_KEY>",
    authDomain: "<PROJECT_ID>.firebaseapp.com",
    databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
    storageBucket: "<BUCKET>.appspot.com",
    messagingSenderId: "<SENDER_ID>",
  };
  firebase.initializeApp(config);
</script>

您可以在配置块中执行此初始化操作 - 类似于下面的示例。请记住,firebase是全局对象。

app.config(function() {
      var config = {
        apiKey: "<API_KEY>",
        authDomain: "<PROJECT_ID>.firebaseapp.com",
        databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
        storageBucket: "<BUCKET>.appspot.com",
        messagingSenderId: "<SENDER_ID>",
      };
      firebase.initializeApp(config);
});

你也可以根据firebase-messaging-sample在某些服务或同一配置块中创建后台消息处理程序。以下是它的gits:
 const messaging = firebase.messaging();
 // [END initialize_firebase_in_sw]
 **/
// If you would like to customize notifications that are received in the
// background (Web app is closed or not in browser focus) then you should
// implement this optional method.
// [START background_handler]
messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  return self.registration.showNotification(notificationTitle,
      notificationOptions);
});

firebase-messaging.js不应该被要求,因为它包含在firebase.js中。需要后台消息处理程序,否则firebase.messaging().getToken()将无法初始化。 - Stamatis Rapanakis

0
你应该检查Firebase Cloud Messaging Quickstart示例。部署时要小心,在/dist文件夹中包含firebase-messaging-sw.js文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接