docs(service-worker): fix example of manually checking for updates (#28020)

Poll for updates in a way that does not prevent the SW from being
registered. Discussed in https://github.com/angular/angular/pull/27332#pullrequestreview-179504620.

PR Close #28020
This commit is contained in:
George Kalpakas 2019-01-09 18:44:47 +02:00 committed by Andrew Kushnir
parent 89a39bb22a
commit 8c3f98fdbb
2 changed files with 23 additions and 9 deletions

View File

@ -1,15 +1,17 @@
import { Injectable } from '@angular/core';
import { ApplicationRef, Injectable } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';
// #docregion sw-check-update
import { interval } from 'rxjs';
import { concat, interval } from 'rxjs';
import { first } from 'rxjs/operators';
@Injectable()
export class CheckForUpdateService {
constructor(updates: SwUpdate) {
interval(6 * 60 * 60).subscribe(() => updates.checkForUpdate());
constructor(appRef: ApplicationRef, updates: SwUpdate) {
// Allow the app to stabilize first, before starting polling for updates with `interval()`.
const appIsStable$ = appRef.isStable.pipe(first(isStable => isStable === true));
const everySixHours$ = interval(6 * 60 * 60 * 1000);
const everySixHoursOnceAppIsStable$ = concat(appIsStable$, everySixHours$);
everySixHoursOnceAppIsStable$.subscribe(() => updates.checkForUpdate());
}
}
// #enddocregion sw-check-update

View File

@ -35,11 +35,23 @@ It's possible to ask the service worker to check if any updates have been deploy
Do this with the `checkForUpdate()` method:
<code-example path="service-worker-getting-started/src/app/check-for-update.service.ts" linenums="false" header="check-for-update.service.ts" region="sw-check-update"> </code-example>
<code-example path="service-worker-getting-started/src/app/check-for-update.service.ts" linenums="false" header="check-for-update.service.ts"> </code-example>
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.
<div class="alert is-important">
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).
</div>
### 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: