我有一个注入到app.component.ts的更新服务,它应该订阅“可用”订阅。但是,在多次部署到我们的登台环境后,我无法访问其中的console.log。启动应用程序时,我看到了logUpdate()和checkForUpdate()的初始console.logs。checkForUpdate()正在被触发,因为我可以看到浏览器每10秒获取一次。但是,在对应用程序进行更改并推送到我们的环境并等待10秒后,available订阅中的代码不会被触发……我的实现是正确的吗?
以下是该服务:
@Injectable({
providedIn: 'root'
})
export class ServiceWorkerService {
constructor(private appRef: ApplicationRef,
private updates: SwUpdate,
private snackbar: MatSnackBar) {
// log and check for updates
}
logUpdate() {
console.log('logUpdate()');
this.updates.available.subscribe(evt => {
console.log('Update Available: ', evt);
const snack = this.snackbar.open('Update Available', 'Reload', {
duration: 6000
});
snack
.onAction()
.subscribe(() => {
window.location.reload();
});
});
this.updates.activated.subscribe(event => {
console.log('old version was', event.previous);
console.log('new version is', event.current);
});
}
checkForUpdate() {
console.log('checkForUpdate()');
// Allow the app to stabilize first, before starting polling for updates with `interval()`.
const appIsStable$ = this.appRef.isStable.pipe(first(isStable => isStable === true));
// const everySixHours$ = interval(6 * 60 * 60 * 1000);
const everySixHours$ = interval(10 * 1000);
const everySixHoursOnceAppIsStable$ = concat(appIsStable$, everySixHours$);
everySixHoursOnceAppIsStable$.subscribe(() => this.updates.checkForUpdate());
}
}ngsw-config.json:
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/assets/favicon.ico",
"/index.html",
"/manifest.webmanifest",
"/*.css",
"/*.scss",
"/*.js"
]
}
},
{
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**",
"/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
]
}
}
]
}和app.component.ts:
export class AppComponent implements OnInit {
environment = environment;
constructor(private swService: ServiceWorkerService) {
}
ngOnInit(): void {
this.swService.logUpdate();
this.swService.checkForUpdate();
}
}发布于 2021-07-08 18:03:47
我有一个类似的代码,但也错过了SwUpdate.available事件。它可以可靠地检测到localhost上的变化(当使用http-server运行时),但不能检测到DEV部署上的变化。
在我的例子中,service-worker在降级模式下运行。您可以通过访问angular文档中描述的ngws/state URL (相对于您的应用程序)来检查这一点:
https://angular.io/guide/service-worker-devops#debugging-the-angular-service-worker
降级模式的原因是功能切换文件:它在本地环境的/assets/下存在一些默认值,并在部署期间覆盖每个阶段。这导致文件的内容哈希不匹配。
排除ngsw-config.json中的文件解决了这个问题。
https://stackoverflow.com/questions/59074244
复制相似问题