1

I've implemented web push notifications for my Angular app using the SwPush component.

Now I've got a similar problem as question Changing application server key in push manager subscription

How do I refresh the subscription when my application server key has changed? Which boils down to:

How do I get the current subscription using SwPush in Angular?

I tried this:

this._swPush.subscription
  .pipe(take(1))
  .subscribe(pushSubscription => {
    if (pushSubscription) {
      console.log('Active subscription', pushSubscription) // never gets called
    }
    else {
      console.log('No active subscription')
    }
  }, err => { console.log("swpush.subscription error", err); })

But when entering the app the call never returns if there has been an active subscription.

Sam
  • 28,421
  • 49
  • 167
  • 247

1 Answers1

1

This happened to me as well, and unfortunately there are several possibilities why this can happen. First of all, there is a difference between registering a serivce worker and activating the service worker. Im not entirely sure (as I am also quite new to this), but you can request notifications once the service worker is registered, but you cannot read the existing one until the service worker is active.

Check your app.module.ts file for the line where you register the service worker, mine looks a bit like this:

...
ServiceWorkerModule.register('/tms-sw-worker.js', {
      enabled: environment.production,
      // Register the ServiceWorker as soon as the app is stable
      // or after 30 seconds (whichever comes first).
      registrationStrategy: 'registerWhenStable:30000'
    }),
...

And then check the docs. This was definitly one of the issues I was having, as I did the same thing you did, but bound by a button click and it suddenly worked. (Now I am using a setTimeout() with a 45 seconds delay.

And apparently (again, not sure), you can also get the existing subscription simply by calling swPush.requestSubscription(...) as you did when you first requested the useres permission for notifications. For me, this returns the same PushSubscription object as swPush.subscription, and this makes sense for me.

Hafnernuss
  • 2,659
  • 2
  • 29
  • 41