【问题标题】:Angular PWA SwUpdate SnackbarAngular PWA SwUpdate Snackbar
【发布时间】:2021-09-07 17:15:09
【问题描述】:

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

到目前为止,它成功了,但checkForUpdate 一次又一次地被触发 -> 我的控制台收到垃圾邮件。我只是无法弄清楚为什么会发生这种情况以及我对SwUpdate的行为的理解错误

我创建了一个stackblitz example 问题是可见的 - 我收到一个错误,我的浏览器不支持 stackblitz 中的服务人员 - 任何想法如何解决这个问题? (使用 chrome 和在 localhost 上运行的普通应用可以正常工作)

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!');
    });
  }
}

提前致谢!

【问题讨论】:

  • 将 htm 添加到 stackblitz
  • html 是什么意思?

标签: angular progressive-web-apps angular-service-worker


【解决方案1】:

原因在如果:

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

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

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

【讨论】:

    猜你喜欢
    • 2020-03-23
    • 2022-08-17
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 2018-11-15
    相关资源
    最近更新 更多