简体   繁体   中英

Where to put Angular PWA update service?

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();
}

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM