我试图为我的角度PWA实现一个逻辑,在这个逻辑中,当一个更新可用时,一个snackbar会被触发,当剪贴栏被关闭时,我想要一个按钮可以让用户手动更新应用程序。(最后一件事目前还没有实现)
到目前为止,它的工作,但checkForUpdate是一次又一次的触发,->,我的控制台是垃圾邮件。我只是不明白为什么会发生这种事,我对SwUpdate的行为有什么误解
我创建了一个可以看到问题的stackblitz示例 --我的浏览器在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!');
});
}
}提前感谢!
发布于 2021-07-08 10:08:29
原因在以下情况:
if (this.swUpdate.available) {
this.openSnackbar();
} else {
console.log('no update found!');
}this.swUpdate.available是一个可观察的,总是存在的。正确的用法是订阅它一次:
this.swUpdate.available.subscribe(() => this.openSnackbar());发布于 2022-06-27 20:19:39
我认为propper和最近的解决方案应该如下所示:
const stableApp: Observable<boolean> = this.applicationRef.isStable.pipe(first(Boolean));
const everyHour: Observable<number> = timer(3 * 1000, 60 * 60 * 1000);
// Checks for an update on start and every hour and waits until the new version is downloaded from the server and ready for activation.
concat(stableApp, everyHour).subscribe(() => this.swUpdate.checkForUpdate());
// "versionUpdates" should be used instead of "available" observable
this.swUpdate.versionUpdates.pipe(
filter(($event: VersionEvent) => $event.type === 'VERSION_READY')
).subscribe(() => {
// Update ready
this.openSnackbar();
});https://stackoverflow.com/questions/68111863
复制相似问题