1

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..

Jim Jimson
  • 2,368
  • 3
  • 17
  • 40

1 Answers1

0

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..

Jim Jimson
  • 2,368
  • 3
  • 17
  • 40