Skip to content

Instantly share code, notes, and snippets.

@FazioNico
Last active September 25, 2023 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FazioNico/884b5897974d5e4b95bca9d21cecc674 to your computer and use it in GitHub Desktop.
Save FazioNico/884b5897974d5e4b95bca9d21cecc674 to your computer and use it in GitHub Desktop.
[For Students] Exemple component that display update notification with Service Worker
import { Component, ViewEncapsulation } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';
import { merge, Observable, of, Subject } from 'rxjs';
import { map } from 'rxjs/operators';
import { ToastOptions } from '@ionic/core';
import { ToastController } from '@ionic/angular';
import { environment } from 'src/environments/environment';
@Component({
selector: 'app-updates-notification',
template: `
<div *ngIf="updateAvailable$|async"> </div>
`,
styles: [``],
encapsulation: ViewEncapsulation.None
})
export class UpdatesNotificationComponent {
updateAvailable$: Observable<boolean | {}>;
closed$ = new Subject<void>();
constructor(
private readonly _updates: SwUpdate,
private readonly _toast: ToastController
) {
console.log('Application updater install: ', environment.production);
this.updateAvailable$ = merge(
of(false),
this.updates.versionUpdates.pipe(
filter((e) => e.type === 'VERSION_DETECTED'),
map(async () => await this._displayNotif()),
map(() => true)
),
this.closed$.pipe(map(() => false))
);
}
async activateUpdate() {
if (!environment.production) {
return
}
awaiit this.updates.activateUpdate()
location.reload();
}
private async _displayNotif() {
console.log('display notification...');
const data = <ToastOptions>{
message: 'Nouvelle mise à jours!',
position: 'bottom',
showCloseButton: true,
closeButtonText: `Update`,
};
const toast = await this._toast.create(data);
await toast.present();
await toast.onDidDismiss()
this.activateUpdate();
}
}
@FazioNico
Copy link
Author

Angular PWA update notification with Ionic`

Install dependencies

  • run ng add @angular/pwa

Usage

  • copy file into your project
  • add component to app.module.ts
  • Insert tag into app.component.htlm
<app-updates-notification></app-updates-notification>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment