Angular PWA SwUpdate 小吃店

Angular PWA SwUpdate Snackbar

我试图为我的 Angular PWA 实现一个逻辑,其中 snackbar 在更新可用时触发,当 snackbar 被关闭时,我希望用户可以使用一个按钮手动更新应用程序。 (最后一件事目前没有实现)

到目前为止一切顺利,但是 checkForUpdate is getting triggert over and over again -> my console is getting spammed. I just can't figure out why this happens and what I understood wrong about the behavior of the SwUpdate

我创建了一个 stackblitz example 问题是可见的 - 我收到一个错误,提示我的浏览器不支持 stackblitz 中的服务工作者 - 有什么解决办法吗? (在本地主机上使用 chrome 和普通应用程序 运行 工作正常)

app.component.ts:

import { ApplicationRef, Component, OnInit } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { SwUpdate } from '@angular/service-worker';
import { interval, concat } from 'rxjs';
import { first } from 'rxjs/operators';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'newApp';
  updateAvailable = false;

  constructor(private snackbar: MatSnackBar, private swUpdate: SwUpdate, private appRef: ApplicationRef) { }

  ngOnInit() {
    this.checkUpdate();
  }

  openSnackbar() {
    const snack = this.snackbar.open('Update Available', 'Install Now!', { duration: 10000 });

    snack
      .onAction()
      .subscribe(() => {
        window.location.reload();
      });
    if(snack.afterDismissed()){
      console.log('afterDismissed: ', snack.afterDismissed())
      // here the button should become available for a manual update by the user
    } else {
      console.log('else: ', snack)
    }
  }

  checkUpdate() {
    //the Jquery stuff is from Angular-website so I guess it should work right?
    const appIsStable$ = this.appRef.isStable.pipe(
      first(isStable => isStable === true)
    );
    const everySixHours$ = interval(60000);
    const everySixHoursOnceAppIsStable$ = concat(appIsStable$, everySixHours$);

    everySixHoursOnceAppIsStable$.subscribe(() => {
      this.swUpdate.checkForUpdate().then(() => console.log('checked!'));
      if (this.swUpdate.available) {
        this.openSnackbar();
      } else {
        console.log('no update found!');
      }
      console.log('update checked!');
    });
  }
}

提前致谢!

原因在 if:

  if (this.swUpdate.available) {
    this.openSnackbar();
  } else {
    console.log('no update found!');
  }

this.swUpdate.available 是一个始终存在的可观察对象。正确的用法是订阅一次:

this.swUpdate.available.subscribe(() => this.openSnackbar());