简体   繁体   中英

How to pass data from Service Worker to Component

I've managed to follow all of the instructions and tutorials to get notifications working in my Angular 9 app when the app is both in the background and the foreground, however I'm using FCM to pass data messages to my application in order to update a realtime dashboard.

In my app.component I have the below:

ngOnInit() {
this.messagingService.requestPermission();
this.message = this.messagingService.currentMessage;

navigator.serviceWorker.addEventListener('message', function(event) {
    console.log('Received a message from service worker: ', event);

    //The below service doesnt exist in this context
    this.messagingService.processMessage(event)

    });
  }

I'm able to process messages in my service when the app is in the foreground, but I can't get data into my service when the app is in the background. Can anyone assist?

This question is similar to this question, but obviously there was a couple of issues with that question..

So I came across this answer that helped me to solve this problem. All that was required was to make the addEventListener an arrow function in order to bind to the this of the component:

ngOnInit() {
this.messagingService.requestPermission();
this.message = this.messagingService.currentMessage;

navigator.serviceWorker.addEventListener('message', (event) => {

    this.messagingService.processMessage(event)

    });
  }

My understanding of 'this' binding is rudamentary at best, so I'd encourage you to do your own reading..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM