postMessage对象从服务工作者到Angular组件

时间:2017-11-09 13:29:10

标签: angular push-notification service-worker postmessage

如何将此有效负载对象传递给angular 4组件?我读到了关于postMessage但它对我不起作用:(有人可以解释如何让它工作正常吗?

服务人员:

messaging.setBackgroundMessageHandler((payload) => {
  const notificationOptions = {
    "body": data.body,
    "icon": "icon.png",
    "click_action": click_action
  };
  postMessage({'test'});
  return self.registration.showNotification(notificationTitle, notificationOptions);
});

组件:

export class AppComponent implements OnInit {

  constructor() {}
  ngOnInit() {
     navigator.serviceWorker.addEventListener('message', function(event) {
      console.log("Got reply from service worker: " + event.data);
   });
    self.addEventListener('message', event => { 
      console.log('MESSAGE: ',event.data); 
   });

  }
}

2 个答案:

答案 0 :(得分:0)

您的Service Worker代码中至少有一个错误。你不能只是 postMessage某个地方,你必须明确地postMessage一个特定的客户端。您必须首先查询由Service Worker控制的客户端,然后查询其中一个客户端。查看Client.postMesssage()的MDN文档。

此外,在您提供的组件代码中,您从不首先注册服务工作者。您只需为通过postMessage API发送的消息添加事件侦听器,但您不需要初始化/注册Service Worker。我真的建议你仔细阅读serviceworke.rs的出色指南: - )

答案 1 :(得分:0)

这是我的工作代码段:

组件:

...
ngOnInit() {
  // Declair service worker variable in Angular Component
  const myServiceWorker = new Worker('path/to/sw.js');
  myServiceWorker.addEventListener('message', this.logWSPostMsg);
}

logWSPostMsg(message) {
  console.log('WS send to Component', message.data);
}
...

服务人员(sw.js)

...
self.postMessage(msg); // It will send msg to Component
...

如果需要将对象从软件发送到组件,则可以这样调用:

self.postMessage({key: "value"});

如果需要从组件到软件的postMessage,请在declair服务工作程序变量myServiceWorker之后,调用:

myServiceWorker.postMessage(msg); // <msg> type any

当然,sw.js需要一个侦听器:

self.onmessage = function (msg) {
  console.log('Component send to WS', msg.data);
}