w3resource

Service worker communication

Importing ServiceWorkerModule into your AppModule doesn't just register the service worker, it also provides a few services you can use to interact with the service worker and control the caching of your app.

SwUpdate service

The SwUpdate service gives you access to events that indicate when the service worker has discovered an available update for your app or when it has activated such an update-meaning it is now serving content from that update to your app.

The SwUpdate service supports four separate operations:

  • Getting notified of available updates. These are new versions of the app to be loaded if the page is refreshed.
  • Getting notified of update activation. This is when the service worker starts serving a new version of the app immediately.
  • Asking the service worker to check the server for new updates.
  • Asking the service worker to activate the latest version of the app for the current tab.

Available and activated updates

The two update events, available and activated, are Observable properties of SwUpdate:

TypeScript Code:

@Injectable()
export class LogUpdateService {

  constructor(updates: SwUpdate) {
    updates.available.subscribe(event => {
      console.log('current version is', event.current);
      console.log('available version is', event.available);
    });
    updates.activated.subscribe(event => {
      console.log('old version was', event.previous);
      console.log('new version is', event.current);
    });
  }
}

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen log-update.service.ts by w3resource (@w3resource) on CodePen.


You can use these events to notify the user of a pending update or to refresh their pages when the code they are running is out of date.

Checking for updates

It's possible to ask the service worker to check if any updates have been deployed to the server. You might choose to do this if you have a site that changes frequently or want updates to happen on a schedule.

Do this with the checkForUpdate() method:

check-for-update.service.ts

TypeScript Code:

@Injectable()
export class LogUpdateService {

  constructor(updates: SwUpdate) {
    updates.available.subscribe(event => {
      console.log('current version is', event.current);
      console.log('available version is', event.available);
    });
    updates.activated.subscribe(event => {
      console.log('old version was', event.previous);
      console.log('new version is', event.current);
    });
  }
}

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen check-for-update.service.ts by w3resource (@w3resource) on CodePen.


This method returns a Promise which indicates that the update check has completed successfully, though it does not indicate whether an update was discovered as a result of the check. Even if one is found, the service worker must still successfully download the changed files, which can fail. If successful, the available event will indicate the availability of a new version of the app.

In order to avoid negatively affecting the initial rendering, ServiceWorkerModule will by default wait for the app to stabilize, before registering the ServiceWorker script. Constantly polling for updates, e.g. with interval(), will prevent the app from stabilizing and the ServiceWorker script will never be registered with the browser.

You can avoid that by waiting for the app to stabilize first, before starting to poll for updates (as shown in the example above).

Note that this is true for any kind of polling done by your application. Check the isStable documentation for more information.

Forcing update activation

If the current tab needs to be updated to the latest app version immediately, it can ask to do so with the activateUpdate() method:

TypeScript Code:

@Injectable()
export class PromptUpdateService {

  constructor(updates: SwUpdate) {
    updates.available.subscribe(event => {
      if (promptUser(event)) {
        updates.activateUpdate().then(() => document.location.reload());
      }
    }); 
  }
}

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen prompt-update.service.ts by w3resource (@w3resource) on CodePen.


Doing this could break lazy-loading into currently running apps, especially if the lazy-loaded chunks use filenames with hashes, which change every version.

Previous: App shell
Next: Service worker configuration



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/angular/service-worker-communication.php