Home > database >  Angular PWA SwUpdate always trigger update and reload
Angular PWA SwUpdate always trigger update and reload

Time:08-17

I have an Ionic PWA with angular. Every packages are in latest versions.

I have a SwupdaterService and in production mode app always reload, like loop, without any updates.

Here my service:

export class SwupdaterService {

  constructor(public updates: SwUpdate) {
    if (updates.isEnabled) {
      interval(6 * 60 * 60).subscribe(() => updates.checkForUpdate()
        .then(() => console.log('checking for updates')));
    }
  }

  public checkForUpdates(): void {
    this.updates.versionUpdates.subscribe(event => this.promptUser());
  }

  private promptUser(): void {
    console.log('updating to new version');

    this.updates.activateUpdate().then((res) => { 
      alert('here!');
      document.location.reload()
    });
  }
}

In app.module I have this:

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

And finnaly my app.component:

export class AppComponent {
  constructor(
    private platform: Platform,
    private sw: SwupdaterService,
    private localizationService: LocalizationService) { }

  async ngOnInit() {
    await this.initializeApp();
  }

  async initializeApp() {
    await this.platform.ready();
    this.sw.checkForUpdates();
    await this.localizationService.setInitialAppLanguage();
  }
}

Someone knows why this happens?

CodePudding user response:

I fix this replacing the checkForUpdates function to this one:

  public checkForUpdates(): void {
    this.updates.versionUpdates.
      pipe(filter((evt): evt is VersionReadyEvent => evt.type === 'VERSION_READY'),
        map(evt => ({
          type: 'UPDATE_AVAILABLE',
          current: evt.currentVersion,
          available: evt.latestVersion,
        }))).subscribe(evt => {
          this.promptUser();
        });
  }

like I saw in service.worker:

  readonly versionUpdates: Observable<VersionEvent>;
    /**
     * Emits an `UpdateAvailableEvent` event whenever a new app version is available.
     *
     * @deprecated Use {@link versionUpdates} instead.
     *
     * The of behavior `available` can be rebuild by filtering for the `VersionReadyEvent`:
     * ```
     * import {filter, map} from 'rxjs/operators';
     * // ...
     * const updatesAvailable = swUpdate.versionUpdates.pipe(
     *   filter((evt): evt is VersionReadyEvent => evt.type === 'VERSION_READY'),
     *   map(evt => ({
     *     type: 'UPDATE_AVAILABLE',
     *     current: evt.currentVersion,
     *     available: evt.latestVersion,
     *   })));
     * ```
     */
  • Related