From 3d828e8a77b8842b342a8ec178f7b1a0901251f5 Mon Sep 17 00:00:00 2001 From: Nicolas Constant Date: Tue, 25 Feb 2020 23:20:58 -0500 Subject: [PATCH] added service-worker service --- .../services/service-worker.service.spec.ts | 12 +++++++ src/app/services/service-worker.service.ts | 35 +++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 src/app/services/service-worker.service.spec.ts create mode 100644 src/app/services/service-worker.service.ts diff --git a/src/app/services/service-worker.service.spec.ts b/src/app/services/service-worker.service.spec.ts new file mode 100644 index 00000000..b49e177f --- /dev/null +++ b/src/app/services/service-worker.service.spec.ts @@ -0,0 +1,12 @@ +import { TestBed } from '@angular/core/testing'; + +import { ServiceWorkerService } from './service-worker.service'; + +xdescribe('ServiceWorkerService', () => { + beforeEach(() => TestBed.configureTestingModule({})); + + it('should be created', () => { + const service: ServiceWorkerService = TestBed.get(ServiceWorkerService); + expect(service).toBeTruthy(); + }); +}); diff --git a/src/app/services/service-worker.service.ts b/src/app/services/service-worker.service.ts new file mode 100644 index 00000000..762d9368 --- /dev/null +++ b/src/app/services/service-worker.service.ts @@ -0,0 +1,35 @@ +import { Injectable, ApplicationRef } from '@angular/core'; +import { SwUpdate } from '@angular/service-worker'; +import { first } from 'rxjs/operators'; +import { interval, concat, BehaviorSubject } from 'rxjs'; + +@Injectable({ + providedIn: 'root' +}) +export class ServiceWorkerService { + + newAppVersionIsAvailable = new BehaviorSubject(false); + + constructor(appRef: ApplicationRef, updates: SwUpdate) { + + //https://angular.io/guide/service-worker-communications + + updates.available.subscribe(event => { + console.log('current version is', event.current); + console.log('available version is', event.available); + + this.newAppVersionIsAvailable.next(true); + }); + + // 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(2 * 60 * 60 * 1000); + const everySixHoursOnceAppIsStable$ = concat(appIsStable$, everySixHours$); + + everySixHoursOnceAppIsStable$.subscribe(() => updates.checkForUpdate()); + } + + loadNewAppVersion() { + document.location.reload(); + } +} \ No newline at end of file