简体   繁体   中英

How to implement Service Worker in Angular for app update notifications

I have installed the angular service worker module and applied the appropriate code to the app module. I have an updateComponent that has the UI to notify the user that there's a new version available with an update button that will reload the page.

However, in a previous version of the service worker, the code to make the notification UI appear and become removed on button click (reload), was the following:

export class LogUpdateService {

  updateAvailable: boolean = false;

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

In the latest version, available has been depreciated.

I have added the following which achieves the UI component notification appearing. When the update button in the notification component is clicked, the page is reloaded (as intended). However, the notification component is still present and doesn't disappear. This component is governed by an ngIf with the updateAvailable boolean from the service below.

export class AppUpdateService {

  updateAvailable: boolean = false;

  constructor(
    private swUpdate: SwUpdate
  ) {

    swUpdate.checkForUpdate().then(() => {
      this.updateAvailable = true;
    });

  }
}

Question

Once the update button in the notification component has been clicked and the page has reloaded, why is updateAvailable still true? Is there another condition in the latest version of the service worker that checks if the update has been applied?

The following seemed to work:

    this.swUpdate.versionUpdates.subscribe((event: VersionEvent) => {
      if (event.type === 'VERSION_READY') {
        // do stuff
      }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM