{ "id": "guide/service-worker-communications", "title": "Service worker communication", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Service worker communicationlink

\n

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.

\n

Prerequisiteslink

\n

A basic understanding of the following:

\n\n

SwUpdate servicelink

\n

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.

\n

The SwUpdate service supports four separate operations:

\n\n

Available and activated updateslink

\n

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

\n\n@Injectable()\nexport class LogUpdateService {\n\n constructor(updates: SwUpdate) {\n updates.available.subscribe(event => {\n console.log('current version is', event.current);\n console.log('available version is', event.available);\n });\n updates.activated.subscribe(event => {\n console.log('old version was', event.previous);\n console.log('new version is', event.current);\n });\n }\n}\n\n\n

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.

\n

Checking for updateslink

\n

It's possible to ask the service worker to check if any updates have been deployed to the server.\nThe service worker checks for updates during initialization and on each navigation request—that is, when the user navigates from a different address to your app.\nHowever, you might choose to manually check for updates if you have a site that changes frequently or want updates to happen on a schedule.

\n

Do this with the checkForUpdate() method:

\n\nimport { ApplicationRef, Injectable } from '@angular/core';\nimport { SwUpdate } from '@angular/service-worker';\nimport { concat, interval } from 'rxjs';\nimport { first } from 'rxjs/operators';\n\n@Injectable()\nexport class CheckForUpdateService {\n\n constructor(appRef: ApplicationRef, updates: SwUpdate) {\n // Allow the app to stabilize first, before starting polling for updates with `interval()`.\n const appIsStable$ = appRef.isStable.pipe(first(isStable => isStable === true));\n const everySixHours$ = interval(6 * 60 * 60 * 1000);\n const everySixHoursOnceAppIsStable$ = concat(appIsStable$, everySixHours$);\n\n everySixHoursOnceAppIsStable$.subscribe(() => updates.checkForUpdate());\n }\n}\n\n\n\n

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 availability of a new version of the app.

\n
\n

In order to avoid negatively affecting the initial rendering of the page, ServiceWorkerModule waits for up to 30 seconds by default for the app to stabilize, before registering the ServiceWorker script.\nConstantly polling for updates, for example, with setInterval() or RxJS' interval(), will prevent the app from stabilizing and the ServiceWorker script will not be registered with the browser until the 30 seconds upper limit is reached.

\n

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

\n

You can avoid that delay by waiting for the app to stabilize first, before starting to poll for updates, as shown in the example above.\nAlternatively, you might want to define a different registration strategy for the ServiceWorker.

\n
\n

Forcing update activationlink

\n

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

\n\n@Injectable()\nexport class PromptUpdateService {\n\n constructor(updates: SwUpdate) {\n updates.available.subscribe(event => {\n if (promptUser(event)) {\n updates.activateUpdate().then(() => document.location.reload());\n }\n });\n }\n}\n\n\n
\n

Calling activateUpdate() without reloading the page could break lazy-loading in a currently running app, especially if the lazy-loaded chunks use filenames with hashes, which change every version.\nTherefore, it is recommended to reload the page once the promise returned by activateUpdate() is resolved.

\n
\n

Handling an unrecoverable statelink

\n

In some cases, the version of the app used by the service worker to serve a client might be in a broken state that cannot be recovered from without a full page reload.

\n

For example, imagine the following scenario:

\n\n

In the above scenario, the service worker is not able to serve an asset that would normally be cached.\nThat particular app version is broken and there is no way to fix the state of the client without reloading the page.\nIn such cases, the service worker notifies the client by sending an UnrecoverableStateEvent event.\nYou can subscribe to SwUpdate#unrecoverable to be notified and handle these errors.

\n\n@Injectable()\nexport class HandleUnrecoverableStateService {\n constructor(updates: SwUpdate) {\n updates.unrecoverable.subscribe(event => {\n notifyUser(\n `An error occurred that we cannot recover from:\\n${event.reason}\\n\\n` +\n 'Please reload the page.');\n });\n }\n}\n\n\n

More on Angular service workerslink

\n

You may also be interested in the following:

\n\n\n \n
\n\n\n" }