Skip to content

Instantly share code, notes, and snippets.

@pnutmath
Created March 7, 2019 09:23
Show Gist options
  • Save pnutmath/b66d98488a8e4a8b04873fff6cf6f514 to your computer and use it in GitHub Desktop.
Save pnutmath/b66d98488a8e4a8b04873fff6cf6f514 to your computer and use it in GitHub Desktop.
Check for PWA application updates in Angular
import { ApplicationRef, Injectable } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';
import { concat } from 'rxjs/observable/concat';
import { interval } from 'rxjs/observable/interval';
import { first } from 'rxjs/operators';
import { NGXLogger } from 'ngx-logger';
import { environment } from 'environments/environment';
import { DialogService } from './dialog.service';
@Injectable()
export class CheckForUpdateService {
constructor(
private appRef: ApplicationRef,
private swUpdate: SwUpdate,
private _logger: NGXLogger,
private _dialog: DialogService) { }
init() {
if (this.swUpdate.isEnabled) {
this.promptOnUpdateAvailable();
this.checkForUpdateAfterInterval(environment.checkForUpdateInterval);
}
}
private promptOnUpdateAvailable() {
this.swUpdate.available.subscribe((event) => {
this._logger.info('Current version is', event.current);
this._logger.info('Available version is', event.available);
this._dialog
.showConfirmDialog(
'Update Available!',
'A new version of EdgeConnect is available. Please update now.',
{ positiveButtonLabel: 'Update', negativeButtonLabel: 'Not Now' }).
result.then((data) => {
if (data === true) {
this._logger.info('User continued with update', event.available);
window.location.reload();
} else {
this._logger.info('User choose to skip update', event.available);
}
}).catch((err) => {
this._logger.log(err);
});
});
}
/**
* Check for updates after interval specified in minutes
* @param minutesInterval interval in minutes
*/
private checkForUpdateAfterInterval(minutesInterval: number) {
this._logger.info('Check for updates initiated!');
// Allow the app to stabilize first, before starting polling for updates with `interval()`.
const appIsStable$ = this.appRef.isStable.pipe(first(isStable => isStable === true));
const everyInterval$ = interval(minutesInterval * 60 * 1000);
const everyIntervalOnceAppIsStable$ = concat(appIsStable$, everyInterval$);
everyIntervalOnceAppIsStable$.subscribe(() => {
this.swUpdate.checkForUpdate();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment