【问题标题】:Where to put Angular PWA update service?Angular PWA 更新服务放在哪里?
【发布时间】:2020-09-25 09:42:09
【问题描述】:

我有一个 PWA 应用正在运行,并且想要整理 application.component。 所以我创建了这个独立的服务来监视 PWA 更新并通知用户:

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

}

我的问题是,我在哪里“调用”此服务,以便在应用启动时创建并运行它? 我试图将它放入 app.module 提供者的部分,但它不会被创建。

我可以在 app.component 中再次导入服务,但我想整理一下。那么我在哪里放置一个自动运行的服务呢?

[更新] 我试图将它导入到我的 app.component 中,但通知不会触发。调用后服务好像会被销毁?

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

【问题讨论】:

    标签: angular service progressive-web-apps swupdate


    【解决方案1】:

    您可以在 app.component.ts 内部调用它,在大多数情况下它是根组件

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

    【讨论】:

    • setupUpdates() 被调用,但我没有收到更新通知。服务似乎已停止。
    • @Sam 更新机制完全是另一回事,尽管服务不会“停止”。我建议调试以查看是否达到了 subscribe() 的回调。然后,您可以从那里找到问题。
    • 是的,我尝试了几次:如果我将this._swUpdate.available.subscribe 放在 app.component 中它可以工作,当我将它移动到服务并从 app.component 调用服务时它不再工作了.它是挑剔的东西!
    猜你喜欢
    • 1970-01-01
    • 2012-01-29
    • 2019-11-11
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    相关资源
    最近更新 更多