import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { environment } from '@environment'; import { catchError, of as observableOf } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ServiceWorkerService { private alerted: boolean; private interval: number|NodeJS.Timeout; constructor ( private http: HttpClient ) { } async checkForUpdate () { // if we are testing or on localhost, don't do this if (!environment.production) { return; } const base = document.head.querySelector('base')?.href; const result = await this.http.get(base + 'version.json').pipe( catchError((e: HttpErrorResponse) => { if (e.status === 404) { // make sure we aren't adding a new alert every 15 seconds this.notifyUpdated('404'); } return observableOf(null); })) .toPromise(); if (result !== environment.version) { this.notifyUpdated(result as any); } } private notifyUpdated (newVersion: string) { if (!this.alerted) { this.alerted = true; if (this.interval) { clearInterval(this.interval as number); } console.warn('There is a new version of GrantsConnect, the browser will now reload. '); } } startPolling () { // if we are testing or on localhost, don't do this if (!environment.production) { return; } this.interval = setInterval(() => { if (!this.alerted) { this.checkForUpdate(); } }, 60000); } }