Where to put Angular PWA update service?

595 views Asked by At

I've got a PWA app running and wanted to declutter the application.component. So I created this self-contained service to watch for PWA updates and notify the user:

import { Injectable } from '@angular/core';

import { MatSnackBar } from "@angular/material/snack-bar";

import { SwUpdate } from "@angular/service-worker";
import { environment } from '../environments/environment';

import { interval } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class PwaUpdatesService {

  constructor(
    private _snackBar: MatSnackBar,
    private _swUpdate: SwUpdate,
  ) {

    if (environment.production) {
      this.setupUpdates();
    }
  }

  setupUpdates() {
    this._swUpdate.available.subscribe(u => {
      this._swUpdate.activateUpdate().then(e => {
        this._snackBar.open("There is an update", "reload app", { duration: 99999 }).onAction().subscribe(
          () => location.reload()
        );
      });
    });

    const everySixHours$ = interval(6 * 60 * 60 * 1000);
    everySixHours$.subscribe(() => this._swUpdate.checkForUpdate());
  }

}

My question is, where do I 'call' this service so it will get created and run on app startup? I tried to put it into the app.module providers' section, but it won't get created.

I could import the service again in the app.component, but I wanted to declutter that one. So where do I put an auto-running service?

[Update] I tried to import it in my app.component, but the notifications won't fire. Does it seem the service will be destroyed after calling them?

constructor(
  private pwaUpdatesService: PwaUpdatesService,
) {
    pwaUpdatesService.setupUpdates();
}
1

There are 1 answers

3
AudioBubble On

You could call it inside of app.component.ts, which is the root component in most cases

constructor(private readonly _pwaService: PwaUpdatesService){
  this._pwaService.setupUpdates();
}